What do I need to do to get twig to process a JavaScript file? I have an html.twig that uses a JavaScript twig. Something like this:
{% extends 'BaseBundle::layout.html.twig' %}
{% block javascripts %}
{{ parent() }}
{% javascripts
'@BaseBundle/Resources/js/main.js.twig'
%}
{% endjavascripts %}
{% endblock %}
< more template omitted >
And parts of main.js.twig:
function testFunction()
{
alert('{{VariableFromPHP}}');
}
And the controller:
/**
* @Route("/",name="home")
* @Template("MyBundle:Default:index.html.twig")
*/
public function indexAction()
{
return array( 'VariableFromPHP' => 'Hello World');
}
I expected the JavaScript to look like this at run-time:
alert('Hello World');
But, the code is unchanged. Any ideas what I am doing wrong?
Thanks, Scott
Twig is a template engine for the PHP programming language. Its syntax originates from Jinja and Django templates. It's an open source product licensed under a BSD License and maintained by Fabien Potencier.
Templates in Symfony are created with Twig: a flexible, fast, and secure template engine.
Twig is a PHP templating language that outputs variables into the HTML of views in MVC (models, views, controllers) programming. So, it contributes to the structure of a website's frontend.
My sugestion to use global variables:
{% javascripts '@AcmeBundle/Resources/public/js/*' output='js/compiled/main.js'%}
<script>
var TWIG = {};
TWIG.variableOne = "{{ path('rote_to_nowhere') }}";
TWIG.variableTwo = "{{ helloworldVar }}";
TWIG.variableThree = "{{ "something"|trans }}";
</script>
<script type="text/javascript" src="{{ asset_url }}"></script>
{% endjavascripts %}
then you can use it in your js
file:
alert(TWIG.variableTwo);
Assetic does not include twig templates; you should create a separate controller for the javascript file. Although I would consider it bad practice performance-wise, because you will have to process two requests this way.
/**
* @Route("/main.js")
*/
public function mainJsAction() {
$params = array( 'test' => 'ok' );
$rendered = $this->renderView( 'MyBundle:Default:main.js.twig', $params );
$response = new \Symfony\Component\HttpFoundation\Response( $rendered );
$response->headers->set( 'Content-Type', 'text/javascript' );
return $response;
}
{% extends 'BaseBundle::layout.html.twig' %}
{% block javascripts %}
{{ parent() }}
<script type="text/javascript" src="{{ path('my_default_mainjs') }}"></script>
{% endblock %}
An alternative is to dump dynamic variables in the html, and only use static javascript files.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With