如何以编程方式设置分支块内容


How to programmatically set twig block content?

是否可以从PHP代码中设置一个twitch模板块的值?我正在从另一个模板引擎迁移,我需要一个桥接器来设置块的值,而不使用树枝模板。

我刚刚得到了我希望在呈现模板之前分配的纯文本。

如果您想在块中包含PHP文件,我建议您创建一个扩展。

样品

index.php

<?php
require(__DIR__ . '/../vendor/autoload.php');
$loader = new Twig_Loader_Filesystem('./');
$twig = new Twig_Environment($loader, array());
$function = new Twig_SimpleFunction('get_php_contents', function($file, $context) {
    ob_start();
    include($file); // $context is available in your php file
    return ob_get_clean();
}, array('is_safe' => array('html')));
$twig->addFunction($function);
echo $twig->render('test.twig', array('name' => 'Alain'));

测试.titch

{% extends 'base.twig' %}
{% block content %}
{{ get_php_contents('contents.php', _context) }}
{% endblock %}

基本树枝

<html>
    <div>I'm a base layout</div>
    {% block content %}{% endblock %}
</html>

contents.php

<?php
echo '<div style="color:red">';
echo "Hello {$context['name']}, it is now: ";
echo date("Y-m-d H:i:s");
echo '</div>';

结果

<html>
    <div>I'm a base layout</div>
    <div style="color:red">Hello Alain, it is now: 2014-10-28 19:23:23</div>
</html>