Issue mixing jquery, rails, and haml

2019-09-17 13:25发布

I'm converting an html.erb into html.haml. I have some jquery in an erb which is..

:javascript
  $(".level").live("click", function() {
    //..some code
    <% if @milestone %>
      milestone = "&milestone=<%= @milestone%>";
    <% end %>
    //..some code
  });

I want to convert the if statement into haml and for that I'm doing..

- if @milestone
  milestone = '&milestone="#{@milestone}"'

but this does not work and gives me a syntax error on "if @milestone"

What am I doing wrong? Can you not mix jquery and haml?

1条回答
祖国的老花朵
2楼-- · 2019-09-17 13:44

Inside the :javascript filter (or any filter) code isn’t treated as Haml, so you can’t use things like - if .... However you can use interpolation with #{...} inside filters. In your case you could do something like:

:javascript
  $(".level").live("click", function() {
    //..some code
    #{"milestone = \"&milestone=#{@milestone};\"" if @milestone}
    //..some code
  });

That is a bit unwieldy with the nested interpolated parts, so you might want to move it into a helper method, something like:

def add_milestone(milestone)
  if milestone
    "milestone = \"&milestone=#{milestone}\";"
  else
    ""
end

Then your Haml would look like

:javascript
  $(".level").live("click", function() {
    //..some code
    #{add_milestone(@milestone)}
    //..some code
  });
查看更多
登录 后发表回答