jQuery get raw text (unescaped) for further parsing via underscore templates

拟墨画扇 提交于 2019-12-12 08:53:36

问题


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?


回答1:


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.




回答2:


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/




回答3:


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

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



来源:https://stackoverflow.com/questions/11909784/jquery-get-raw-text-unescaped-for-further-parsing-via-underscore-templates

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