英文:
Display html characters in Svelte
问题
我有一个 Svelte 应用 REPL,我希望将字符串转换为 HTML 字符。
<h1>Test html codes</h1>
{#each lines|| [] as line}
<div id="comment-line">
{line}
</div>
{/each}
<script>
let rawData = [
'Abc',
'Xyz!tm',
'Mno'
]
$: lines = parseLines(rawData)
function parseLines(array) {
let new_array = []
var new_line
for (var line of array) {
new_line = line.replaceAll('!tm', '™');
new_array.push(new_line)
}
return new_array
}
</script>
这个答案 建议使用 *.innerHTML*
,但在 Svelte 中是否可以以更简单的方式完成呢?
英文:
I have a Svelte app REPL where I wish to convert strings to html characters.
<h1>Test html codes</h1>
{#each lines|| [] as line}
<div id="comment-line">
{line}
</div>
{/each}
<script>
let rawData = [
'Abc',
'Xyz!tm',
'Mno'
]
$: lines = parseLines(rawData)
function parseLines(array) {
let new_array = []
var new_line
for (var line of array) {
new_line = line.replaceAll('!tm', '&trade;');
new_array.push(new_line)
}
return new_array
}
</script>
This answer suggests that you use .innerHTML, but can it be done in a more straightforward way in Svelte?
答案1
得分: 3
在Svelte中,你可以使用{@html line}
,这将以纯HTML形式输出_line_,从而获得所需的效果。但要注意,这是不安全的,只能用于你绝对信任的字符串,通常不要用于用户生成的内容。(例如,如果字符串包含脚本,它将运行该脚本)
或者考虑使用new_line = line.replaceAll('!tm', '™');
。
英文:
In Svelte you can use {@html line}
which will output line as pure html getting the effect you require. Be aware though that is inherently insecure and should only be done with strings you absolutely trust and likely never with user-generated content. (if the string contains a script it will run it for example)
Alternatively consider doing new_line = line.replaceAll('!tm', '™');
instead.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论