Sasha Koss
Sasha Koss

Reputation: 16396

Change rails view output from helper

I have rails helpers (hs_if, hs_else):

= hs_if :current_user do
  Hello, {{ current_user/name }}!

  = hs_else do
    = link_to 'Sign In', sign_in_path

...which produces handlebars templates:

{{#if current_user}}
  Hello, {{ current_user/name }}!
{{else}}
 <a href="/signin">Sign In</a>
{{/if}}

How can I render {{#if current_user}} ... {{else}} ... {{/if}} without nesting hs_else in hs_if?

I think I should remove {{/if}} from output, but I can't find way to do it in helper.

Upvotes: 1

Views: 280

Answers (2)

Anatoly
Anatoly

Reputation: 15530

I think the conditional expression to check current_user can be used in helper (outside the mustache template):

module M::TemplatesHelper
  def hs_header(&block)
    if current_user
      "Hello, {{ current_user/name }}!"
    else
      link_to('Sign In', sign_in_path)
    end.html_safe
  end
end

Upvotes: 0

wanderfalke
wanderfalke

Reputation: 878

I think the easiest way would be to introduce a separate method for the closing if tag (i.e. hs_endif) and remove {{/if}} part from hs_if. So that you could write something like this:

= hs_if :current_user do
  Hello, {{ current_user/name }}!
= hs_else do
  = link_to 'Sign In', sign_in_path
= hs_endif

You'll have to type a bit more, but it might make a code a bit clearer. Of course there is a danger that you forget to close your if-statement, but you'll have you unit tests to catch this anyways, right?

Upvotes: 1

Related Questions