You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Lit框架中&(与符号)的翻译转义异常问题求助

Lit组件含&符号的翻译文本显示异常解决方案

问题场景

在Lit组件模板中,使用msg()函数的字符串包含&符号:

<sdx-input
  type="search"
  placeholder="${msg("Hilfe & Community durchsuchen")}"
  @input=${this.searchHandler}
>

由于&是XML特殊字符,翻译生成的XLF文件中会被转义为&amp;:

<trans-unit id="sb55e20f5aee93270">
  <source>Hilfe &amp; Community durchsuchen</source>
  <target>Search Help &amp; Community</target>
</trans-unit>

但翻译后的文本未自动转回HTML格式,导致页面显示异常(如直接显示Search Help &amp; Community而非Search Help & Community)。当前临时方案是通过DOM解析解码:

const decodedTranslation = new DOMParser().parseFromString("Search Help &amp; Community", 'text/html').documentElement.textContent

有效解决方法

1. 配置i18n工具自动解码

如果使用Lit官方的@lit/localize工具,可在初始化本地化时开启实体解码配置。例如生成本地化模块时添加--decode-entities参数,确保翻译文本中的XML实体被自动解码后注入模板,无需手动处理。

2. 轻量JS解码函数替代DOM解析

避免DOM解析的额外开销,可实现纯JS的XML实体解码函数,处理常见实体:

function decodeXMLEntities(str) {
  return str.replace(/&amp;/g, '&')
            .replace(/&lt;/g, '<')
            .replace(/&gt;/g, '>')
            .replace(/&quot;/g, '"')
            .replace(/&apos;/g, "'");
}

在模板中直接调用:

<sdx-input
  type="search"
  placeholder="${decodeXMLEntities(msg("Hilfe & Community durchsuchen"))}"
  @input=${this.searchHandler}
>

3. 优化翻译提取流程

检查i18n提取工具的配置,确保提取模板字符串时,不对原始的&进行不必要的转义。调整提取规则,将模板中的&作为普通字符处理,避免写入XLF文件时被转为&amp;,从根源上解决双重转义问题。

内容的提问来源于stack exchange,提问作者codepleb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 05:18:13