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

Shopware 6如何通过JavaScript获取自定义插件的翻译文本?

在Shopware 6中从自定义插件翻译文件获取文本到JavaScript

下面是几种可靠的实现方式,替代你尝试的window变量方案:

方法1:通过Twig模板传递翻译到原生JS

在插件的Twig模板中,先通过Shopware的翻译函数$trans()拿到文本,再通过DOM的data属性传递给JS:

<!-- 你的插件模板文件(比如src/Resources/views/storefront/page/product-detail/my-plugin.html.twig) -->
<div class="my-custom-plugin" data-search-text="{{ $trans('search.config.text') }}"></div>

<script>
document.addEventListener('DOMContentLoaded', function() {
  const pluginElement = document.querySelector('.my-custom-plugin');
  const translatedText = pluginElement.dataset.searchText;
  console.log(translatedText); // 输出"testing"
});
</script>

方法2:在Shopware JS模块中使用LocaleService

如果你的插件基于Shopware的前端模块系统开发,直接注入LocaleService来获取翻译:

// 插件的JS文件(比如src/Resources/app/storefront/src/js/my-plugin.js)
import LocaleService from 'src/service/locale.service';

// 直接获取翻译文本
const searchConfigText = LocaleService.trans('search.config.text');
console.log(searchConfigText); // 输出"testing"

确保你的翻译文件路径正确:放在src/Resources/app/storefront/locale/目录下,命名为对应语言的JSON文件(比如en-GB.json、zh-CN.json),Shopware会自动加载这些文件。

方法3:在Vue组件中直接使用翻译方法

如果你的插件使用Vue组件开发,可直接用Shopware提供的全局翻译方法:

<!-- 插件的Vue组件文件 -->
<template>
  <div class="search-config-text">{{ $t('search.config.text') }}</div>
</template>

<script>
export default {
  mounted() {
    // 在JS逻辑中获取翻译
    const text = this.$t('search.config.text');
    console.log(text); // 输出"testing"
  }
}
</script>

关键注意事项

  • 翻译键名必须完全匹配:你的翻译JSON中键是search.config.text,调用时要严格一致,包括层级结构。
  • 翻译文件路径要正确:必须放在插件的src/Resources/app/storefront/locale/目录下,文件名符合语言代码规范(如en-GB.json)。
  • 避免使用window变量:Shopware的官方翻译机制更稳定,不会造成全局变量污染,也能自动适配当前店铺语言。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 19:22:49