具有以下 lodash 模板源
<script id="resume-template" type="text/html">
<tr>
<td>Curriculum</td>
<td>
<%= _.unescape(resume.curriculum) %>
</td>
</tr>
</script>
并且具有以下上下文
const context = {
resume: {
email: '...',
firstName: '...',
lastName: '...',
curriculum: "&lt;p&gt;some important information goes here&lt;/p&gt;\r\n&lt;p&gt;unordered list&lt;/p&gt;\r\n&lt;ul&gt;\r\n&lt;li&gt;item1&lt;/li&gt;\r\n&lt;li&gt;item2&lt;/li&gt;\r\n&lt;li&gt;item3&lt;/li&gt;\r\n&lt;li&gt;item4&lt;/li&gt;\r\n&lt;/ul&gt;\r\n&lt;p&gt;ordered list&lt;/p&gt;\r\n&lt;ol&gt;\r\n&lt;li&gt;pet1&lt;/li&gt;\r\n&lt;li&gt;pet2&lt;/li&gt;\r\n&lt;li&gt;pet3&lt;/li&gt;\r\n&lt;li&gt;pet4&lt;/li&gt;\r\n&lt;/ol&gt;\r\n&lt;p&gt;Some &lt;span style=&quot;text-decoration: line-through;&quot;&gt;&lt;span style=&quot;text-decoration: underline;&quot;&gt;&lt;strong&gt;other&lt;/strong&gt;&lt;/span&gt;&lt;/span&gt; &lt;span style=&quot;text-decoration: underline;&quot;&gt;information&lt;/span&gt; &lt;span style=&quot;text-decoration: line-through;&quot;&gt;goes&lt;/span&gt; &lt;strong&gt;here&lt;/strong&gt;&lt;/p&gt;"
}
}
以及以下实现
const app = document.querySelector('#app');
const resume = response; // ajax response
const source = document.querySelector('#resume-template').innerHTML;
const template = _.template(source);
app.innerHTML = template(resume);
我需要将resume.curriculum键的内容呈现为html,为了实现此目的,我首先对resume.curriculum内容进行转义<%= _.unscape(resume.curriculum) %>
,但我没有获取 html,而是获取 html 标签及其内容作为文本
作为帮助,如果在模板中我放置以下内容 <%= '<p><i>Some content</i></p>' %>
适本地呈现为 html
感谢您为解决此情况提供的任何帮助
最佳答案
在服务器端代码中的某个位置,您对 curriculum
字段进行了双重转义。看到这个 block :
&lt;p&gt;some important information goes here&lt;/p&gt;
应该是:
<p>some important information goes here</p>
所以,修复你的服务器端代码,你就会看到你的东西开始工作。要验证这一点,只需更改以下内容:
<td>
<%= _.unescape(resume.curriculum) %>
</td>
至:
<td>
<%= _.unescape(_.unescape(resume.curriculum)) %>
</td>
关于javascript - 尝试在模板内呈现 html 内容时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50805610/