Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
741 views
in Technique[技术] by (71.8m points)

symfony - variable Twig in 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>

where these parameters are set in config.yml

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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() }};

Or call each parameter of the user like {{ app.user.id }}

Documentation : https://twig.sensiolabs.org/doc/filters/json_encode.html

You should use json_encode for your variables above, if you have a quote into one of your string it will break your javascript.

Example for profile:

<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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...