Symfony2、树枝和 JavaScript

2022-01-22 00:00:00 php symfony twig

我需要做什么才能让 twig 处理 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 不包含 twig 模板;您应该为 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 SymfonyComponentHttpFoundationResponse( $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.

相关文章