Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Function for transfering variables from Twig to JS #4915

Closed
piotrpog opened this issue Sep 11, 2019 · 1 comment

Comments

@piotrpog
Copy link

commented Sep 11, 2019

I often pass Twig variables into JS. I do this like this:

{% js %}
var js_variable = '{{twig_variable}}'
{% endjs %}

This is little cumbersome. I propose simplifying this process with function like this:

{{twigToJs(variable, 'js_variable_name')}}

This would output:

var js_variable_name = 'twig_variable_contents'

If second argument would not be provided, js variable name would be same as twig variable name.

If object or array was used instead of simple twig variable, it would be passed through json encode function.

If twig variable was boolean instead of string, function could skip wrapping js variable in '.

@brandonkelly

This comment has been minimized.

Copy link
Member

commented Sep 11, 2019

You can already do this using the json_encode filter.

var js_variable_name = {{ twig_variable|json_encode|raw }}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
2 participants
You can’t perform that action at this time.