douyeke2695 2014-10-28 14:29
浏览 12
已采纳

如何以编程方式设置树枝块内容?

Is it possible to set the value of a twig template block from PHP code? I'm migrating from a different template engine and I need a bridge to set the value of blocks without using a twig template.

I've just got plain text that I was hoping to assign before I render the template.

  • 写回答

1条回答 默认 最新

  • doulou1970 2014-10-28 18:25
    关注

    If you want to include PHP files inside blocks, I suggest you to create an extension.

    Sample

    <kbd>index.php</kbd>

    <?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'));
    

    <kbd>test.twig</kbd>

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

    <kbd>base.twig</kbd>

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

    <kbd>contents.php</kbd>

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

    Result

    <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>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类