外部 JS 文件中的 Twig 变量 [英] Twig variable in external JS file
问题描述
我想外部化我的 JS 代码,但代码中有 Twig 变量.
你有什么技巧可以让它发挥作用?
I would like to externalize my JS code, but there is Twig variable in the code.
What are your tricks to make this working?
team: {{ 'Select your team'|trans }}
推荐答案
当您需要将 twig 变量传递给外部 javascript 文件时,有两种方法
There a two approaches when you need to pass a twig variable to an external javascript file
- 在树枝模板的脚本块内定义变量
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script>
var my_twig_var = {% if twig_var is defined %}'{{ twig_var }}'{% else %}null{% endif %}
</script>
<script src="scripts/functions.js"></script>
</body>
</html>
对于这种方法,我通常添加一个名为javascript"的块;阻止我的主/基本模板
For this approach I usally add a block called "javascript" block in my main/base template
base.twig.html
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
{% block body %}
{% endblock %}
{% block javascript %}
{% endblock %}
</body>
</html>
page.html.twig
{% extends base.twig.html %}
{% block body%}
<h1>Hello World</h1>
{% endblock %}
{% block javascript %}
<script>
alert('{{ twig_var|default('Hello World') }}');
</script>
{% endblock %}
- 借助
data-*
属性将变量传递给javascript
- Pass the variables to javascript with the aid of
data-*
attributes
<div data-foo="{{ foo }}">...</div>
$(function() {
$(document).on('click', '.button', function(e) {
console.log($('div[data-foo]').data('foo'));
});
});
旁注:如果您想将对象或数组传递给 twig
,您始终可以使用 json_encode
过滤器,它将变量转换为有效的 javascript 对象
Sidenote: if you want to pass an object or an array to twig
you can always use the json_encode
filter, which will convert the variable to a valid javascript object
如果您想控制 json_encode
过滤器公开哪些对象属性,您可以始终实现接口 Serializable
If you want to have control over which object properties are exposed by the json_encode
filter you can always implement the interface Serializable
这篇关于外部 JS 文件中的 Twig 变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!