简体   繁体   English

在symfony2中创建事件以渲染树枝文件

[英]Create event in symfony2 to render a twig file

I'm new to symfony2 and I'm looking for solution to create an event that render a twig file. 我是symfony2的新手,我正在寻找解决方案以创建一个渲染树枝文件的事件。

Assume we have a base template 假设我们有一个基本模板

<!DOCTYPE html>
<html>
<head>
    {% block meta %}{% endblock %}
    <title>{% block title %}Welcome!{% endblock %}</title>
    {% block stylesheets %}{% endblock %}
</head>
<body data-cachetime="{{ cacheTimeStamp() }}">
    {% block header %}{% endblock %}
    <div id="content">
        <div class="container">
            {% block content %}{% endblock %}
        </div>
    </div>
    {% block footer %}{% endblock %}
    {% block version %}{% endblock %}
    {% block javascripts %}{% endblock %}
    {% block trackers %}{% endblock %}
</body>
</html>

As you can see, I've a "version" block. 如您所见,我有一个“版本”块。 I've created an VersionBundle which read the version from a file. 我创建了一个VersionBundle,它从文件中读取版本。 The version twig template 版本树枝模板

{% block version %}
    <div id="version"><p>Version: {{ versionString() }}</p></div>
{% endblock %}

calls an "ViewHelper" (i came from Zend ;-)) which calls the function from VersionBundle. 调用一个“ ViewHelper”(我来自Zend ;-),它从VersionBundle中调用该函数。 But now the tricky part: The VerionBundle is only registered for 'dev' and 'test' Environment in the AppKernel. 但是现在棘手的是:VerionBundle仅在AppKernel中注册了“开发”和“测试”环境。 Thats why i create the 'version' block instead of calling the ViewHelper directly in the base twig file. 这就是为什么我创建“版本”块而不是直接在基本树枝文件中调用ViewHelper的原因。

But i don't know how to create an event to render the version twig template first so the data will passed to the base twig. 但是我不知道如何创建一个事件来首先渲染版本树枝模板,因此数据将传递到基础树枝。

I would maybe change the way you try to do it, using more Symfony features and avoiding defining Zend like "helpers". 我可能会更改您尝试执行此操作的方式,使用更多的Symfony功能并避免像“助手”那样定义Zend。 It's a good rule of thumb to keep Twig as minimal as it can be, just rendering view from data the templates receive. 保持Twig尽可能的小是一个很好的经验法则,只是从模板接收的数据中渲染视图。

First, define the version variable in parameters_dev.yml and parameters_test.yml files (in app/config ). 首先,在parameters_dev.ymlparameters_test.yml文件(在app/config )中定义version变量。 Example: 例:

parameters:
    version: 32

Define it as version: ~ in parameters.yml . 将其定义为version: ~parameters.yml

Make this variable available in all Twig templates in the app/config/config.yml file: 使此变量在app/config/config.yml文件的所有Twig模板中可用:

twig:
    globals:
        version: %version%

Then, in your version block definition, do the following: 然后,在您的version块定义中,执行以下操作:

{% block version %}
    {% if version is not null %}
        <div id="version"><p>Version: {{ version }}</p></div>
    {% endif %}
{% endblock %}

Hope it helps! 希望能帮助到你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM