如何在 JavaScript 中使用反引号来进行字符串插值并提取 HTML 原始代码?

huangapple go评论63阅读模式
英文:

How to fetch HTML raw code in Backtick for string interpolation in js?

问题

我正在制作简历生成器,HTML 模板文件保存在 Firebase 存储中,我使用 URL 获取数据。模板已经被修改以进行字符串插值,例如 <h1>${name}</h1>。现在,当我使用 Axios 获取数据时,name 变量已经在组件中定义,并且使用 dangerouslySetInnerHTML 渲染 HTML 在 React 中时,它显示的是与插值之前一样的 HTML。我知道可以使用反引号来解决,但如何解决以使 HTML 被反引号包围呢。
这就是我想要的:

name = 'react'
const data = axios.get(url)
// data = '<h1>${name}</h1>';

return (
  <div dangerouslySetInnerHTML={{ __html: data }} />
)

期望的输出: React
实际输出: ${name}

英文:

I'm making resume builder, the html template file is saved in firebase storage and using url i fetch the data. Template is already been modified for string interpolation for example &lt;h1&gt;${name}&lt;/h1&gt;. now when i fetch the data using axio and the name variable is already been defined in component and using dangerouslysetinnerhtml i render the html in react. its shows the html exactly like how it is without interpolation. I know it can be done using backtick but how to work around to make it like the html is surrounded by backtick.
This is what is want:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

name = &#39;react&#39;
const data = axios.get(url)
//data = &#39;&lt;h1&gt;${name}&lt;/h1&gt;&#39;

return (
&lt;div dangerouslySetInnerHTML={{ __html: data }} /&gt;
)

<!-- end snippet -->
Expected Output: React
Actual output: ${name}

答案1

得分: 1

使用合适的模板引擎通常是最佳选择,因为它将保护您免受跨站脚本攻击的威胁。

然而,如果您不需要担心跨站脚本攻击(例如,因为HTML文件被视为源文件,即硬编码且仅由您编辑),那么您可以使用eval:

const name = 'bob';
const data = '<h1>${name}</h1>';
const result = eval('`' + data + '`');
console.log(result) // <h1>bob</h1>
英文:

Using a proper template engine is usually the best approach, because it will protect you from XSS.

However, if you don't need to worry about XSS (for example because the HTML files are treated like source files i.e hardcoded and only edited by you), then you can use eval:

const name = &#39;bob&#39;;
const data = &#39;&lt;h1&gt;${name}&lt;/h1&gt;&#39;
const result = eval(&#39;`&#39;+data+&#39;`&#39;);
console.log(result) // &lt;h1&gt;bob&lt;/h1&gt;

huangapple
  • 本文由 发表于 2023年2月23日 23:55:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/75547249.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定