7

I currently have an html modal block like so:

<div id="modal">
   <div class="header_buttons"></div>
   <p> 
       Are you sure you would like to perform <%= action_name %> 
       on <%= count %> objects?
   </p>
   <div class="footer_buttons">
        <button>Do <%= action_name %></button>
   </div>
</div>

I'd like to parse this content through _.template

$("#modal").html() //-> escapes `<%` 
$("#modal").text() //-> doesn't escape, but doesn't include tags. 

My immediate solution is to target each element instead of the whole block so that I can use text() but I'm curious if there's an obvious solution here otherwise?

3 Answers 3

10

A solution you see a lot is to put HTML embedded templates in script tags, which are not HTML escaped.

So transforming your div into:

<script id="modal" type="text/template">
   ...
</script>

...would make $("#modal").html() return the raw HTML.

Of course if there's some reason you need it to be in a div, then this isn't for you.

3
  • That's the way. I'll delete my answer. Aug 10, 2012 at 22:19
  • It does need to be a div to trigger the modal but I like it! I wonder how I can use this while making it work with a modal plugin (using bootstrap-modal). Aug 10, 2012 at 22:45
  • You could just put the templates outside the modal and then render the html in the modal before opening it. $('#modal').html(rendered).modal() or something similar. Aug 11, 2012 at 15:35
4

Just use .html(), then search and replace your template tags:

$("#modal").html().replace(/&lt;%=/g, '<%=').replace(/%&gt;/g, '%>');

Here's the fiddle: http://jsfiddle.net/PwL7L/

7
  • And what happens when the template contains an id attribute? Aug 10, 2012 at 22:34
  • I'm using this but converting all <% to capture _ javascript blocks Aug 11, 2012 at 4:07
  • @muistooshort - Care to explain what you mean by that? How would that affect any of this? Aug 12, 2012 at 4:39
  • If the template has an id attribute and the template is stored inside a <div>, you'll end up with two elements in the DOM with the same id attribute. You now have invalid HTML and you can expect strange things to happen with certain id selectors. Aug 12, 2012 at 4:42
  • @muistooshort - Oh! That comment should have been on the question, not on the answer... Aug 12, 2012 at 4:43
1

_.unescape should help you use div instead of script.

_.unescape($("#modal").html());

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.