Symfony2、树枝和 JavaScript [英] Symfony2, twig and JavaScript

查看:17
本文介绍了Symfony2、树枝和 JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要做什么才能让 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.

这篇关于Symfony2、树枝和 JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆