英文:
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 <h1>${name}</h1>
. 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 = 'react'
const data = axios.get(url)
//data = '<h1>${name}</h1>'
return (
<div dangerouslySetInnerHTML={{ __html: data }} />
)
<!-- 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 = 'bob';
const data = '<h1>${name}</h1>'
const result = eval('`'+data+'`');
console.log(result) // <h1>bob</h1>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论