gpt4 book ai didi

javascript - js文件中的eex语法或Phoenix代码

转载 作者:行者123 更新时间:2023-11-30 11:24:01 25 4
gpt4 key购买 nike

我的 index.html.eex 中的内部标记我可以使用此语法来检索文本。

<%= gettext "Login failed!"%>

现在我有一个用于验证字段的 js 文件,我将此文件作为脚本加载到 index.html.eex 中。

一切正常,但我需要在 js 文件中使用 gettext 进行 Phoenix 文本翻译。我知道 <%= %> 语法不会在 .eex 文件之外编译,但是我拒绝将我所有的验证逻辑代码放在 index.html.eex 中我该怎么做才能在 js 文件中获取 phoenix 代码?

最佳答案

您可以将翻译存储在 index.html.eex 中的变量中然后从 JS 文件访问它。这是一个例子:

将此添加到 index.html.eex 的顶部:

<script>
var Translations = {
"login_failed": <%= raw Poison.encode!(gettext("Login failed!")) %>,
};
</script>

现在在你的 JS 文件中,做:

console.log(Translations.login_failed)

更好的方法是创建此类翻译的列表并将它们注入(inject)布局文件:

<script>
var Translations = {
"login_failed": <%= raw Poison.encode!(gettext("Login failed!")) %>,
"some_other_error": <%= raw Poison.encode!(gettext("Some other error!")) %>,
};
</script>

这样所有翻译都将在 app.js 中可用.


为什么 rawPoison.encode!

简单地做 "<%= thing %>"'<%= thing %>'如果 thing 将会中断包含引号或换行符(可能还有一些其他特殊字符)。 Poison.encode!会将值转换为有效的 JSON(这也是有效的 JS)和 raw将确保此值不会被双重转义。

关于javascript - js文件中的eex语法或Phoenix代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48704167/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com