简体   繁体   中英

How to programmatically set twig block content?

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.

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

Sample

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

test.twig

{% extends 'base.twig' %}

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

base.twig

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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