Twig模板无法包含PHP模板。

5
我遇到了一个问题,对我来说非常不清楚和难以理解。我尝试制作一个日历小部件,应该在我的网站的每个页面上显示。所以,我认为它应该是平均模板(没有参数,没有每个网站)。我尝试将其作为twig模板。我设法渲染出了日历,但是我遇到了获取日期对象的问题(这是获取正确参数来渲染日历所必需的)。过了一会儿,我尝试制作一个php模板,该模板将被主twig模板(layout.html.twig)包含。但是没有成功。我已经在config.yml中启用了php引擎,但没有帮助-实际上包括了php模板,但作为普通文件而不是php文件(未解析为php脚本),(但是php引擎正在工作,我尝试从控制器呈现php模板它可以正常工作)。我还阅读了可以在模板中包括来自另一个控制器的结果,但对我来说这不是正确的解决方案,我没有尝试过(php模板应该适合此问题)。
我该怎么做才能解决这个问题?
主config.yml
imports:
    - { resource: parameters.ini }
    - { resource: security.yml }

framework:
    #esi:             ~
    translator:      { fallback: %locale% }
    secret:          %secret%
    charset:         UTF8
    router:          { resource: "%kernel.root_dir%/config/routing.yml" }
    form:            true
    csrf_protection: true
    validation:      { enable_annotations: true }
    templating:      { engines: ['twig', 'php'] }
    session:
        default_locale: %locale%
        auto_start:     true

# Twig Configuration
twig:
    debug:            %kernel.debug%
    strict_variables: %kernel.debug%

# Assetic Configuration
assetic:
    debug:          %kernel.debug%
    use_controller: false
    # java: /usr/bin/java
    filters:
        cssrewrite: ~
        # closure:
        #     jar: %kernel.root_dir%/java/compiler.jar
        # yui_css:
        #     jar: %kernel.root_dir%/java/yuicompressor-2.4.2.jar

# Doctrine Configuration
doctrine:
    dbal:
        driver:   %database_driver%
        host:     %database_host%
        port:     %database_port%
        dbname:   %database_name%
        user:     %database_user%
        password: %database_password%
        charset:  UTF8

    orm:
        auto_generate_proxy_classes: %kernel.debug%
        auto_mapping: true

# Swiftmailer Configuration
#swiftmailer:
#    transport: %mailer_transport%
#    host:      %mailer_host%
#    username:  %mailer_user%
#    password:  %mailer_password%

jms_security_extra:
    secure_controllers:  true
    secure_all_services: false

# services:
#    TpsaMailer:

#        class: Tpsa\TestBundle\Controller\MailerController

layout.html.twig

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

{% block stylesheets %}
<link rel="stylesheet" type="text/css"
href="{{ asset('bundles/tpsablog/css/main.css') }}">
{% endblock %}

{% block javascripts %}
<!-- empty javascripts -->
{% endblock %}

<title>
{% block title %}
{% trans %}blog.programisty.duga{% endtrans %}
{% endblock %}
</title>

</head>
<body>
<div id="all">
    <div id="top">
        {% block top %}
            <div style="float: left" class="right">
                            <img style="float: left;
                            vertical-align: middle; margin: 8px
                            8px 8px 0px" src="{{ asset('bundles/tpsablog/images/glider.png') }}">
                <h4>{% trans %}blog.programisty.duga{% endtrans %}</h4>
                <div style="font-size: 8px">
                    {% trans %}ciekawosc.wiedza.niewygodne{% endtrans %}
                    <!-- Ciekawość i wiedza... To, co jest niewygodne dla
                    władzy -->
                </div>

            </div>
            <div style="float: right">
                <a href="{{ path('HomePage') }}">{% trans %}strona.glowna{% endtrans %}</a>
                <a href="{{ path('AboutPage') }}">{% trans %}o.mnie{% endtrans %}</a>
                <a href="{{ path('TBB_mess_add') }}">{% trans %}napisz.do.mnie{% endtrans %}</a>
                {% if is_granted('IS_AUTHENTICATED_FULLY') %}
                {{ app.user.username }}
                <a href="{{ path('TBB_tag_list_homepage') }}">{% trans %}tagi{% endtrans %}</a>
                <a href="{{ path('TBB_mess_list_homepage') }}">{% trans %}wiadomosci{% endtrans %}</a>
                <a href="{{ path('logout') }}">{% trans %}wyloguj{% endtrans %}</a>
                {% else %}
                <a href="{{ path('login') }}">{% trans %}zaloguj{% endtrans %}</a>
                {% endif %}
                <div style="text-align: center; margin: 10px 0px">
                <a href="{{ path('TBB_rss') }}">
                <img src="{{ asset('bundles/tpsablog/images/rss.png')
                }}" alt="rss channel">  
                </a>
                <a href="http://www.facebook.com/duga.chernobyl"
                target="_blank">
                <img src="{{ asset('bundles/tpsablog/images/facebook.png') }}"
                alt="facebook"> 
                </a>
                <a href="http://www.youtube.com/user/DugaEye"
                target="_blank">
                <img src="{{ asset('bundles/tpsablog/images/youtube.png') 
                }}" alt="youtube">
                </a>
                </div>
            </div>
            <div style="clear:both"></div>
        {% endblock %}
    </div>

    <div id="frame">
        <div id="left">
        {% block content %}
            {% trans %}TODO{% endtrans %}
        {% endblock %}
        </div>
        <div id="right">
        {% block panel %}
            <div style="text-align: left">
                <div style="text-align: center">    
                <h4>{% trans %}profil.duga.eye{% endtrans %}</h4>
                <img style="width: 100px" src="{{
                asset('bundles/tpsablog/images/photo.jpg')
                }}">
                </div>
                <div style="font-weight:900; margin-top: 10px">
                <ul>
                <li>{% trans %}wiek{% endtrans %}: 21</li>
                <li>{% trans %}miejsce{% endtrans %}: /dev/null</li>
                <li>{% trans %}zainteresowania{% endtrans %}: {% trans %}programowanie.hacking.filozofia{% endtrans %}</li>
                <li>{% trans %}email{% endtrans %}: <a
                href="mailto:duga(dot)eye(at)gmx(dot)com">Mail</a>
                </ul>
                </div>
            </div>
            <h3>{% trans %}reklamy{% endtrans %}</h3>
            {% include '::calendar.html.php' %}
        {% endblock %}
        </div>
    </div>

    <div id="footer">
        {% block footer %}
        {% trans %}footer{% endtrans %}
        {% endblock %}
    </div>


</div>
</body>
</html>

如何从php Date对象中获取正确的参数偏移量、数量、结束时间和当前时间?(现在是硬编码的)
calendar.html.twig
{% include '::calendar.html.php' %}

{% set offset = 1 %}
{% set number = 28 %}
{% set koniec =  7 - ((offset + number) % 7) %}
{% set aktualny = 13 %}
<table border="0" style="text-align: center">
<thead>
<tr>
<td>{% trans %}pn{% endtrans %}</td>
<td>{% trans %}wt{% endtrans %}</td>
<td>{% trans %}sr{% endtrans %}</td>
<td>{% trans %}czw{% endtrans %}</td>
<td>{% trans %}pt{% endtrans %}</td>
<td>{% trans %}sob{% endtrans %}</td>
<td>{% trans %}nie{% endtrans %}</td>
</tr>
<tbody>
{% if offset % 7 != 0 %}
<tr>
{% for i in range(0,offset-1,1) %}<td><br></td>{% endfor %}
{% endif %}
{% for i in 1..number %}
{% if (i+offset)%7 == 1 %}<tr>{% endif %}
<td>
{% if i == aktualny %}
<span style="color: red">{{ i }}</span>
{% else %}
{{ i }}

{% endif %} 

</td>
{% if (i+offset)%7 == 0  %}</tr>{% endif %}
{% endfor %}
{% if koniec  < 7 %}
{% for i in 1..koniec %}
<td><br></td>
{% endfor %}
</tr>
{% endif %}
</tbody>
</table>

这是一个 PHP 模板,应该在 Twig 模板中作为 PHP 模板包含,但它没有像一个模板那样被解析和执行。

calendar.html.php

ppp<?php echo  ('ala') ?>ooo

只需在源代码中包含“pppooo”,不可见的被视为HTML标记。

如果需要,可以使用依赖文件。

[symfony]
    git=http://github.com/symfony/symfony.git
    version=v2.0.9

[twig]
    git=http://github.com/fabpot/Twig.git
    version=v1.5.1

[monolog]
    git=http://github.com/Seldaek/monolog.git
    version=1.0.2

[doctrine-common]
    git=http://github.com/doctrine/common.git
    version=2.1.4

[doctrine-dbal]
    git=http://github.com/doctrine/dbal.git
    version=2.1.5

[doctrine]
    git=http://github.com/doctrine/doctrine2.git
    version=2.1.5

[swiftmailer]
    git=http://github.com/swiftmailer/swiftmailer.git
    version=v4.1.5

[assetic]
    git=http://github.com/kriswallsmith/assetic.git
    version=v1.0.2

[twig-extensions]
    git=http://github.com/fabpot/Twig-extensions.git

[metadata]
    git=http://github.com/schmittjoh/metadata.git
    version=1.0.0

[SensioFrameworkExtraBundle]
    git=http://github.com/sensio/SensioFrameworkExtraBundle.git
    target=/bundles/Sensio/Bundle/FrameworkExtraBundle
    version=origin/2.0

[JMSSecurityExtraBundle]
    git=http://github.com/schmittjoh/JMSSecurityExtraBundle.git
    target=/bundles/JMS/SecurityExtraBundle
    version=origin/1.0.x

[SensioDistributionBundle]
    git=http://github.com/sensio/SensioDistributionBundle.git
    target=/bundles/Sensio/Bundle/DistributionBundle
    version=origin/2.0

[SensioGeneratorBundle]
    git=http://github.com/sensio/SensioGeneratorBundle.git
    target=/bundles/Sensio/Bundle/GeneratorBundle
    version=origin/2.0

[AsseticBundle]
    git=http://github.com/symfony/AsseticBundle.git
    target=/bundles/Symfony/Bundle/AsseticBundle
    version=v1.0.1
3个回答

6

在一个响应中,您不能混用Twig和PHP(这样做会规避Twig的部分目的,即防止设计师在视图中创建过多的逻辑)。

我认为Symfony文档应该/可以对此更加清晰(目前它基本上说“启用它们并做你想做的事情”)。

如果嵌入另一个控制器,则应该能够提供不同的响应,并且 那个 响应可以是基于PHP的。


2

注意:以下代码片段完全未经测试。

http://twig.sensiolabs.org/doc/functions/date.html

函数date似乎创建了一个\DateTime对象。

{% set now = date() %}
{% set offset = date(now.format('Y/m/01')).format(w) %} {# weekday of 1st day #}
{% set number = now.format('t') %} {# days in month #}
{% set koniec = 7 - ((offset + number) % 7) %}
{% set aktualny = now.format('n') %} {# today #}

然而,如果您想在Twig中包含原始的php文件(比如'calendar.php'),您需要编写扩展程序来使其工作。

class CalendarExtension extends \Twig_Extension
{
    private $pathToPhp; //store that where the php file is

    public function setPhpFile($pathToPhp)
    {
        $this->pathToPhp = $pathToPhp;
    }

    public function getFunctions()
    {
        return array(
            new \Twig_SimpleFunction('calendar', array($this, 'showCalendar'))
        );
    }

    public function showCalendar([put arguments here if you need])
    {
        ob_start();
        include ($this->pathToPhp);
        return ob_get_clean();
    }
}

为了使上述工作正常运行,您应该在容器中创建“标记”服务。
in app/config/config.yml

services:
    calendar_twig_extension:
        class: __Namespace__\CalendarExtension
        calls:
            - [setPhpFile, [__path to your calendar.php__]]
        tags:
            - [name: twig.extension]

需要替换的双下划线单词:

  • _ _ Namespace _ _ :CalendarExtension的命名空间
  • _ _ path to your calendar.php _ _ :calendar.php的完整路径。您可以使用%kernel.root_dir%等参数来管理与项目相关的路径。

有了这些,你最终可以简单地写出

{{ calendar([arguments for CalendarExtension::showCalendar]) }}

1
你考虑过使用 {% render 'ApplicationBundle:Controller:action' %} 渲染你的日历 PHP 模板,并在 action 中渲染 PHP 模板吗?
你也可以在渲染日历 Twig 的 action 中渲染你的日历 PHP,并将 PHP 模板的输出作为一个简单的 Twig 变量传递。
注意:如果变量中有任何 HTML 标签,请不要忘记使用 {{ var|raw }} 来显示它。
注意2:从 Symfony2.2 开始,渲染参数已更改为 {% render url('route_name') %}

从Symfony 2.2.x开始,render参数再次更改为{{ render(controller('ApplicationBundle:Controller:action')) }} - denkiryokuhatsuden

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接