Javascript中的变量Twig [英] variable Twig in Javascript
问题描述
我怎样才能将{{app.user}}传递给Javascript?
How can i pass {{app.user}} into Javascript ?
现在我做了一个像这样的块;
for now I do a block like;
<script type="text/javascript">
var app_name = '{{ app_name }}';
var app_url= '{{ app_url }}';
var app_description= '{{ app_description }}';
var app_email= '{{ app_email }}';
var app_title= '{{ app_title }}';
var app_dominio= '{{ app_dominio }}';
var env = '{{ app.environment }}';
</script>
这些参数在config.yml中设置
where these parameters are set in config.yml
推荐答案
我不明白您选择的解决方案究竟是什么问题,它应该与{{app.user}}一起使用,除了app.user是一个对象,所以你应该在你的用户中使用toArray函数并调用:
I don't understand what's exactly your problem with the solution you choose, it should work well with {{ app.user }} except that app.user is an object, so you should have a toArray function into your user and call :
app_user = {{ app.user.toArray|json_encode() }};
或调用用户的每个参数,如{{app.user.id}}
Or call each parameter of the user like {{ app.user.id }}
文档: https://twig.sensiolabs.org/doc/filters/json_encode.html
你应该使用json_encode为你的上面的变量,如果你的一个字符串中有引号,它将破坏你的javascript。
You should use json_encode for your variables above, if you have a quote into one of your string it will break your javascript.
个人资料示例:
<script type="text/javascript">
nickname = {{ profile.nickname|json_encode() }}; // Nickname will be a string
// 2nd solution if you have more informations related to profile
profile = {
nickname: {{ profile.nickname|json_encode() }},
lastname: {{ profile.lastname|json_encode() }}
};
// Profile is now an object with a nickname property.
// use profile.nickname on your javascripts
</script>
这篇关于Javascript中的变量Twig的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!