Rendering “<%%=” with HAML

2019-04-14 16:32发布

问题:

I have a Backbone.js application hosted in Sinatra and rendered via an ERB script. The backbone templates are using the underscore template functionality so the variables are rendered in ERB like so:

<div id="<%%= variable %>">

The extra "%" escapes the rendering of that variable and renders it with a single "%" which is what the underscore template library would pick up.

I tried the following while upgrading to HAML:

#"<%= id %>"

Which did not work. How do I accomplish the same task with HAML?

回答1:

First, you can’t use the # shortcut to create an id with a value like that, you’ll have to do it the long way:

%div{:id => "<%= id %>"}

By default, Haml will escape the attributes, so this will produce something like:

<div id='&lt;%= id %&gt;'></div>

which is probably not what you want. You can turn of escaping of attributes by setting the :escape_attrs option to false. This will then produce the desired output:

<div id='<%= id %>'></div>

Note that this option effects all attributes in the document.

An alternative would be to use a different set of delimiters in your templates. For example you could use {{...}} with this:

_.templateSettings = {
  interpolate : /\{\{(.+?)\}\}/g
};

Now Haml won’t escape the attribute values.



标签: haml erb