显示Svelte中的HTML字符

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

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', '&trade;');
            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.

&lt;h1&gt;Test html codes&lt;/h1&gt;
{#each lines|| [] as line}
    &lt;div id=&quot;comment-line&quot;&gt;
        {line}
    &lt;/div&gt;
{/each}


&lt;script&gt;
    let rawData = [
	    &#39;Abc&#39;,
	    &#39;Xyz!tm&#39;,
	    &#39;Mno&#39;
    ]
    $: lines = parseLines(rawData)
    
    function parseLines(array) {
	    let new_array = []
	    var new_line
	    for (var line of array) {
		    new_line = line.replaceAll(&#39;!tm&#39;, &#39;&amp;trade;&#39;);
		    new_array.push(new_line)
	    }
	    return new_array
    }
&lt;/script&gt;

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(&#39;!tm&#39;, &#39;™&#39;); instead.

huangapple
  • 本文由 发表于 2023年6月5日 14:41:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76404032.html
匿名

发表评论

匿名网友

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

确定