在 Assetic 资产中翻译 JavaScript 文字字符串的最佳方法是什么?

发布于 2024-11-28 00:53:26 字数 733 浏览 1 评论 0原文

我正在使用 Symfony2 开发一个可翻译的应用程序。该应用程序启用了 Assetic,可以缩小和合并 *.js*.css 文件。但是,我编写了一个 jQuery 插件,其中包含文字字符串。例如,考虑以下代码:

       $('<p>Are you sure you want to proceed?</p>').dialog({
            buttons: {
                "Yes" : function() {
                    // ...
                },
                "No" : function() {
                    // ...
                }
            }
        });

在上面的代码片段中,“Are you certain...”、“Yes”和“No”将始终是英语,并且我无法在 .js 文件中使用 Twig 模板来翻译它使用类似: {{ "yes"|trans }}

我想知道的是,使用 Twig 来利用内置的 Symfony2 翻译机制来翻译文字字符串的最佳方式是什么在我的 JS 脚本中。

有没有办法创建例如: myscript.js.twig 文件?

I'm using Symfony2 to develop a application that is to be translatable. The application has Assetic enabled to minify and combine *.js and *.css files. However, I have a jQuery plugin I wrote, that has literal strings in it. For example, consider the following code:

       $('<p>Are you sure you want to proceed?</p>').dialog({
            buttons: {
                "Yes" : function() {
                    // ...
                },
                "No" : function() {
                    // ...
                }
            }
        });

In the above snippet, "Are you sure...", "Yes" and "No" will always be English, and I can't use Twig templating in the .js file to translate it using something like: {{ "yes"|trans }}

What I want to know is, what would be the best way to use Twig to leverage the built in Symfony2 translation mechanism, to translate the literal strings in my JS scripts.

Is there a way to create for example: myscript.js.twig files?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

谁的年少不轻狂 2024-12-05 00:53:26

有没有办法创建例如:myscript.js.twig 文件?

这似乎是个坏主意。


您可以检查 https://github.com/willdurand/BazingaExposeTranslationBundle

或自己创建它,例如包含此在您的模板中:

<script type="text/javascript">
    var translations = {
       // ... 
       'yes' : {{ 'yes' | trans }},
       // ...
    }
</script>

如果您的 javascript 文件包含在 之前,您可以在其中使用 translations 变量。

Is there a way to create for example: myscript.js.twig files?

It seems a bad idea.


You can check https://github.com/willdurand/BazingaExposeTranslationBundle

or create it yourself, for example include this in your template:

<script type="text/javascript">
    var translations = {
       // ... 
       'yes' : {{ 'yes' | trans }},
       // ...
    }
</script>

then if your javascript file is included just before </body> you can use translations variable in it.

淡莣 2024-12-05 00:53:26

这是一个在 Symfony 4 和 5 上测试的解决方案。

首先,我们创建一个控制器,它将根据当前语言环境创建一个包含所有翻译的 JavaScript 文件:

<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Yaml\Yaml;

/**
 * Translation controller.
 */
class TranslationController extends AbstractController
{
    /**
     * @Route("/translation.js", name="translation")
     */
    public function index(Request $request)
    {

        $locale = $request->getLocale();
        $file   = __DIR__.'/../../translations/messages.'.$locale.'.yaml';
        $parsed = Yaml::parse(file_get_contents($file));

        $translations = $this->renderView(
            'translation/translation.js.twig', 
            array(
                'json' => json_encode($parsed)
            )
        );

        return new Response($translations, 200,
            array('Content-Type' => 'text/javascript')
        );
    }
}

然后我们创建一个 Twig 模板来呈现响应:

{# /templates/translation/translation.js.twig) #}

var trans = JSON.parse('{{ json|raw }}');

我们放置动态生成的模板中的翻译文件位于其他资产之前:

script src="{{ path('translation') }}"></script>

对于示例翻译文件 /translations/messages.pl.yaml:

projects: Projekty
medium: Średnio
month:
  january: Styczeń
  february: Luty

我们可以在任何 JavaScript 文件中显示我们的翻译:

console.log(trans['month']['january']);
console.log(trans['medium']);

我希望它对某人有用。

Here is a solution, tested on Symfony 4 and 5.

First, we create a controller that will create a JavaScript file with all the translations according to the current locale:

<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Yaml\Yaml;

/**
 * Translation controller.
 */
class TranslationController extends AbstractController
{
    /**
     * @Route("/translation.js", name="translation")
     */
    public function index(Request $request)
    {

        $locale = $request->getLocale();
        $file   = __DIR__.'/../../translations/messages.'.$locale.'.yaml';
        $parsed = Yaml::parse(file_get_contents($file));

        $translations = $this->renderView(
            'translation/translation.js.twig', 
            array(
                'json' => json_encode($parsed)
            )
        );

        return new Response($translations, 200,
            array('Content-Type' => 'text/javascript')
        );
    }
}

Then we create a Twig template to render the response:

{# /templates/translation/translation.js.twig) #}

var trans = JSON.parse('{{ json|raw }}');

We place our dynamically generated translation file in the template before other assets:

script src="{{ path('translation') }}"></script>

For sample translation file /translations/messages.pl.yaml:

projects: Projekty
medium: Średnio
month:
  january: Styczeń
  february: Luty

We can display our translation in any JavaScript file:

console.log(trans['month']['january']);
console.log(trans['medium']);

I hope it will be useful to someone.

风苍溪 2024-12-05 00:53:26

我正在搜索一些东西使 twig.js 与翻译一起工作这似乎我喜欢最好的解决方案。但仍在寻找。

与此同时,我正在使用 jsgettext,它是由 Joshua I 编写的 Javascript 中的 gettext 实现。磨坊主。由于原始存储库已关闭,我已将其上传回 github。

<script language="javascript" src="/path/LC_MESSAGES/myDomain.json"></script>
<script language="javascript" src="/path/Gettext.js"></script>

您将翻译文件加载到 DOM 中,jsgettext 可以解析它:

function _(msgid) { return gt.gettext(msgid); }

alert(_("some string"));

要从 Symfony 获取翻译文件的路径,您必须围绕 Translator 服务创建一些 php/twig 扩展,但它可以很好地工作,而无需复制翻译资源。

I was searching something to make twig.js work with translations which seems to me like the best solution. Still searching though.

In the meantime, I'm using this jsgettext which is a gettext implementation in Javascript, by Joshua I. Miller. I've uploaded back to github since the original repo is down.

<script language="javascript" src="/path/LC_MESSAGES/myDomain.json"></script>
<script language="javascript" src="/path/Gettext.js"></script>

You load your translation files into your DOM and jsgettext can parse it:

function _(msgid) { return gt.gettext(msgid); }

alert(_("some string"));

To get the path of your translation files from Symfony, you'll have to make some php/twig extension around the Translator service but it works great without duplicating your translation resources.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文