Issue mixing jquery, rails, and haml

浪尽此生 提交于 2019-12-11 16:35:18

问题


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:


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
  });


来源:https://stackoverflow.com/questions/16408182/issue-mixing-jquery-rails-and-haml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!