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

基于自定义框架的Twig弹窗内容翻译方案咨询

解决方案:Twig动态弹窗翻译(无需额外PHP翻译文件)

方案1:提前渲染翻译内容到页面隐藏容器,JS调用复用

直接在页面中用Twig把弹窗所需的翻译文本渲染到隐藏元素里,JS动态创建弹窗时从这里取内容,完全复用现有Twig翻译机制:

<!-- 隐藏的翻译内容容器 -->
<div id="popup-translation-store" style="display: none;">
  <span data-trans-key="popup_title">{{ 'popup.title'|trans }}</span>
  <span data-trans-key="popup_content">{{ 'popup.content'|trans }}</span>
  <span data-trans-key="popup_confirm">{{ 'popup.confirm_btn'|trans }}</span>
</div>

JS逻辑示例:

// 获取翻译内容
function getPopupTrans(key) {
  return document.querySelector(`#popup-translation-store [data-trans-key="${key}"]`).textContent;
}

// 创建弹窗
function showPopup() {
  const popupDiv = document.createElement('div');
  popupDiv.innerHTML = `
    <h3>${getPopupTrans('popup_title')}</h3>
    <p>${getPopupTrans('popup_content')}</p>
    <button>${getPopupTrans('popup_confirm')}</button>
  `;
  document.body.appendChild(popupDiv);
  // 后续显示逻辑...
}

方案2:将翻译内容注入JS变量,直接在弹窗逻辑中使用

通过Twig把翻译文本直接渲染成JS全局变量,JS弹窗代码直接调用:

<script>
  // 用Twig翻译过滤器生成JS变量
  const popupI18n = {
    title: "{{ 'popup.title'|trans }}",
    content: "{{ 'popup.content'|trans({'%item%': '商品X'}) }}", // 支持动态参数
    cancelBtn: "{{ 'popup.cancel_btn'|trans }}"
  };
</script>

JS弹窗逻辑:

function showPopup() {
  const popup = document.createElement('div');
  popup.className = 'popup';
  popup.innerHTML = `
    <div class="popup-header">${popupI18n.title}</div>
    <div class="popup-body">${popupI18n.content}</div>
    <div class="popup-footer">
      <button>${popupI18n.cancelBtn}</button>
    </div>
  `;
  document.body.appendChild(popup);
}

方案3:AJAX请求Twig渲染好的弹窗片段(复杂弹窗适用)

后端新增一个接口,返回用Twig预渲染完成的弹窗HTML(已包含翻译),JS需要弹窗时异步请求该接口:

// 后端接口示例(复用现有Twig环境)
public function getPopupHtml() {
  $twig = $this->getTwigEnvironment();
  // 传入弹窗所需参数
  return $twig->render('popup/fragment.twig', [
    'user' => $this->getCurrentUser()
  ]);
}

popup/fragment.twig内容:

<div class="popup">
  <h3>{{ 'popup.welcome'|trans({'%name%': user.name}) }}</h3>
  <p>{{ 'popup.welcome_desc'|trans }}</p>
</div>

JS请求逻辑:

async function showPopup() {
  const response = await fetch('/api/get-popup-html');
  const popupHtml = await response.text();
  const popupDiv = document.createElement('div');
  popupDiv.innerHTML = popupHtml;
  document.body.appendChild(popupDiv);
}

核心说明

以上方案全部复用Twig原生的|trans翻译过滤器,不需要额外创建独立的PHP翻译文件,彻底避免两套翻译机制的维护成本。如果需要处理动态参数,直接在Twig渲染阶段传入即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 01:13:13