Symfony2,Twig和JavaScript [英] Symfony2, twig and JavaScript
问题描述
我需要怎么做才能使树枝处理JavaScript文件?我有一个使用JavaScript树枝的html.twig.像这样:
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 >
main.js.twig的一部分:
And parts of main.js.twig:
function testFunction()
{
alert('{{VariableFromPHP}}');
}
和控制器:
/**
* @Route("/",name="home")
* @Template("MyBundle:Default:index.html.twig")
*/
public function indexAction()
{
return array( 'VariableFromPHP' => 'Hello World');
}
我希望JavaScript在运行时看起来像这样:
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?
谢谢, 斯科特
推荐答案
Assetic不包含树枝模板;您应该为javascript文件创建一个单独的控制器.尽管我认为从性能角度来讲这是不好的做法,因为您将不得不以这种方式处理两个请求.
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 %}
一种替代方法是在html中转储动态变量,并且仅使用静态javascript文件.
An alternative is to dump dynamic variables in the html, and only use static javascript files.
这篇关于Symfony2,Twig和JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!