JQuery gets raw text (unescaped) for further parsing underline patterns

I currently have a html modal block:

<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 would like to analyze this content through _.template

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

My immediate solution is to target every element, not the entire block, so I can use it text(), but I'm curious if there is an obvious solution there?

+5
source share
3 answers

The solution you see a lot is to place the embedded HTML templates in script tags that are not HTML escaped.

So, we will convert yours divto:

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

... will $("#modal").html()return raw HTML.

, - , div, .

+8

.html(), :

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

: http://jsfiddle.net/PwL7L/

+4

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

.

_ escaping in ($ ("# modal") HTML ().);

+1
source

All Articles