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
510 views
in Technique[技术] by (71.8m points)

php - Using Javascript variable in Twig template using Silex framework

I am trying to create a route inside of some Javascript inside of a Twig template and need to use a JS variable as a value to a route parameter.

Example:

window.location.href = {{ path('post_display', { 'id': this_is_where_i_need_to_use_the_js_var }) }};

I am using the Silex framework and am unsure if FOS JS works for Silex. I don't think it does, though.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Twig, since it's written in PHP, runs on the server, completely separately than the javascript code, so what you want needs a workaround.

First, generate the route, but with a placeholder, then replace that with the value of your variable when neccessary:

var route = "{{ path('post_display', { 'id': "PLACEHOLDER" }) }}";
window.location = route.replace("PLACEHOLDER", js_variable);

Something like this should work for you.


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

2.1m questions

2.1m answers

60 comments

57.0k users

...