I'm rewriting an application using the Silex framework. In this application, users can comment on posts and comments. In the non-MVC application, inspired by this question, I wrote it like this:
function display_comments($postid, $parentid=0, $level=0){
// Get the current comment from DB and display with HTML code
display_comments($needid, $comment['id'], $level+1);
}
However, in the Silex application, I want to retrieve them comment(s) from the database in a repository, send it to a twig-template in the controller and finally display the HTML code in the template. This makes the previous solution incompatible.
What is a good solution for this problem in Silex? What do I put in the view, what in the controller and what in the model?
EDIT
I wrote the function in the controller now:
$app->get('/needdetail/{id}', function ($id) use ($app) {
$need = $app['need']->findNeed($id);
function display_comments($app, $needid, $comments=array(), $parentid=0, $level=0){
$replies = $app['comment']->findByNeed($needid, $parentid);
foreach($replies as $reply){
$reply['level'] = $level;
array_push($comments, $reply);
display_comments($app, $needid, $comments, $reply['id'], $level+1);
}
return $comments;
}
return $app['twig']->render('needdetail.html', array('need' => $need, 'comments' => display_comments($app, $id)));
})
The level 0 comments are now shown, but a deeper level isn't.
I managed to get the required result with a slightly different approach. The controller as well as the view contains a recursive function:
Controller:
$app->get('/needdetail/{id}', function ($id) use ($app) {
$need = $app['need']->findNeed($id);
function get_comments($app, $needid, $parentid=0){
$comments = array();
$replies = $app['comment']->findByNeed($needid, $parentid);
foreach($replies as $comment){
$comment['replies'] = get_comments($app, $needid, $comment['id']);
array_push($comments, $comment);
}
return $comments;
}
return $app['twig']->render('needdetail.html', array('need' => $need, 'comments' => get_comments($app, $id)));
})
View:
{% for comment in comments %}
{% include 'comment.html' with {'level': 0} %}
{% endfor %}
Comment.html:
<div class="comment">
//Comment HTML
</div>
{% if comment.replies %}
{%for reply in comment.replies %}
{% include 'comment.html' with {'comment': reply, 'level': level+1} %}
{% endfor %}
{% endif %}
I'm developing a navigation system for Symfony 2. It's working really nicely so far. So far, there is a config file like so:
# The menu name ...
primary:
# An item in the menu ...
Home:
enabled: 1
# Routes where the menu item should be shown as 'active' ...
routes:
- "a_route_name"
# Where the link goes to ... the problem ...
target: "a_route_name"
This layout is working nicely, and the menu works. Apart from in my template, I can only generate links using the target value that correspond to routes within an application; i.e, not an external URL.
The template is as follows for generating the navigation:
{# This is what puts the data for the menu into the page currently ... #}
{% set primary_nav = menu_data('primary') %}
<nav role="navigation" class="primary-nav">
<ul class="clearfix">
{% for key, item in primary_nav if item.enabled is defined and item.enabled %}
{% if item.routes is defined and app.request.attributes.get('_route') in item.routes %}
<li class="active">
{% else %}
<li>
{% endif %}
{% if item.target is defined %}
{{ key }}
{% else %}
{{ key }}
{% endif %}
</li>
{% endfor %}
</ul>
</nav>
Is there a simple way to allow the path() function or, something similar to generate URLs from routes, or just simply use a given URL if it validates as one?
I got as far as trying url(), and looked around the docs but couldn't see anything.
You can create a Twig extension that check if a route exists :
if it exists, the corresponding generated url is returned
else, the url (or other stuff) is returned without any change
In your services.yml, declare your twig extension and inject the router component.
Add the following lines and change namespaces :
fuz_tools.twig.path_or_url_extension:
class: 'Fuz\ToolsBundle\Twig\Extension\PathOrUrlExtension'
arguments: ['#router']
tags:
- { name: twig.extension }
Then create a Twig\Extension directory in your bundle, and create PathOrUrlExtension.php :
<?php
namespace Fuz\ToolsBundle\Twig\Extension;
use Symfony\Bundle\FrameworkBundle\Routing\Router;
class PathOrUrlExtension extends \Twig_Extension
{
private $_router;
public function __construct(Router $router)
{
$this->_router = $router;
}
public function getFunctions()
{
return array(
// will call $this->pathOrUrl if pathOrUrl() function is called from twig
'pathOrUrl' => new \Twig_Function_Method($this, 'pathOrUrl')
);
}
public function pathOrUrl($pathOrUrl)
{
// the route collection returns null on undefined routes
$exists = $this->_router->getRouteCollection()->get($pathOrUrl);
if (null !== $exists)
{
return $this->_router->generate($pathOrUrl);
}
return $pathOrUrl;
}
public function getName()
{
return "pathOrUrl";
}
}
You can now use your new function :
{{ pathOrUrl('fuz_home_test') }}
<br/>
{{ pathOrUrl('http://www.google.com') }}
Will display :
I have divs with CSS that represent boxes, they wrap html code.
<div class="box indent">
<div class="padding">
my code here
</div>
</div>
I created a "layoutbundle" where every HTML wrapper (such as boxes, tabs, grids, and so on) is put inside separate twig files. In such a way, views on other bundles can be implemented with other layouts.
But I get tired of includes. Every small html wrapper requires an include, and I wonder if there is a simpler way to wrap HTML code.
Let's have an example with a simple box. Actually, I created several files :
A box.html.twig file that contain the box and include the content :
<div class="box indent">
<div class="padding">
{% include content %}
</div>
</div>
Several box-content.html.twig files, containing content of my boxes.
And finally, I create a box in a view by doing :
{%
include 'AcmeDemoBundle:layout:box.html.twig'
with {
'content': 'ReusableBundle:feature:xxx.html.twig'
}
%}
Is there a way to create wrappers such as :
a) I declare once a new wrapper :
{% wrapperheader "box" %}
<div class="box indent">
<div class="padding">
{% endwrapperheader %}
{% wrapperfooter "box" %}
</div>
</div>
{% endwrapperfooter %}
b) And then in my pages, I use :
{% wrapper "box" %}
{# here my content #}
{% endwrapper %}
I think I'll need to add new tag extensions in Twig, but first I want to know if something similar is natively possible.
The block method
This method was proposed by Sebastiaan Stok on GitHub.
This idea uses the block function. It writes the given block contents, and can be called several times.
Wrappers file :
{# src/Fuz/LayoutBundle/Resources/views/Default/wrappers.html.twig #}
{% block box_head %}
<div class="box indent">
<div class="padding">
{% enblock %}
{% block box_foot %}
</div>
</div>
{% enblock %}
Feature page :
{{ block('box_head') }}
Some content
{{ block('box_foot') }}
The wrap extension with macros
This idea was proposed by Charles on GitHub.
First you declare a macro in a macro.html.twig file.
{% macro box(content) %}
<div class="box indent">
<div class="padding">
{{ content | raw }}
</div>
</div>
{% endmacro %}
Amd then, instead of calling {{ macros.box('my content') }} (see the doc you develop a {% wrap %} tag that will handle the macro call, with what's between [% wrap %} and {% endwrap %} as parameter.
This extension was easy to develop. I thought it could be hard to access macros, but in fact, they are stored in the context as objects, and calls can be compiled easily.
Just some changes : we will use the following syntax :
{# to access a macro from an object #}
{% wrap macro_object macro_name %}
my content here
{% endwrap %}
{# to access a macro declared in the same file #}
{% wrap macro_name %}
macro
{% endwrap %}
In the following code, don't forget to change namespaces if you want to get it work!
First, add the extension in your services.yml:
parameters:
fuz_tools.twig.wrap_extension.class: Fuz\ToolsBundle\Twig\Extension\WrapExtension
services:
fuz_tools.twig.wrap_extension:
class: '%fuz_tools.twig.wrap_extension.class%'
tags:
- { name: twig.extension }
Inside your bundle, create a Twig directory.
Add the extension, it will return the new TokenParser (in english: it will declare the new tag).
Twig/Extension/WrapExtension.php:
<?php
// src/Fuz/ToolsBundle/Twig/Extension/WrapExtension.php
namespace Fuz\ToolsBundle\Twig\Extension;
use Fuz\ToolsBundle\Twig\TokenParser\WrapHeaderTokenParser;
use Fuz\ToolsBundle\Twig\TokenParser\WrapFooterTokenParser;
use Fuz\ToolsBundle\Twig\TokenParser\WrapTokenParser;
class WrapExtension extends \Twig_Extension
{
public function getTokenParsers()
{
return array (
new WrapTokenParser(),
);
}
public function getName()
{
return 'wrap';
}
}
Then add the TokenParser itself, it will be met when the parser will find a {% wrap %} tag. This TokenParser will check if the tag is called correctly (for our example, it has 2 parameters), store those parameters and get the content between {% wrap %} and {% endwrap %}`.
Twig/TokenParser/WrapTokenParser.php:
<?php
// src/Fuz/ToolsBundle/Twig/TokenParser/WrapTokenParser.php
namespace Fuz\ToolsBundle\Twig\TokenParser;
use Fuz\ToolsBundle\Twig\Node\WrapNode;
class WrapTokenParser extends \Twig_TokenParser
{
public function parse(\Twig_Token $token)
{
$lineno = $token->getLine();
$stream = $this->parser->getStream();
$object = null;
$name = $stream->expect(\Twig_Token::NAME_TYPE)->getValue();
if ($stream->test(\Twig_Token::BLOCK_END_TYPE))
{
if (!$this->parser->hasMacro($name))
{
throw new \Twig_Error_Syntax("The macro '$name' does not exist", $lineno);
}
}
else
{
$object = $name;
$name = $stream->expect(\Twig_Token::NAME_TYPE)->getValue();
}
$this->parser->getStream()->expect(\Twig_Token::BLOCK_END_TYPE);
$body = $this->parser->subparse(array ($this, 'decideWrapEnd'), true);
$this->parser->getStream()->expect(\Twig_Token::BLOCK_END_TYPE);
return new WrapNode($object, $name, $body, $token->getLine(), $this->getTag());
}
public function decideWrapEnd(\Twig_Token $token)
{
return $token->test('endwrap');
}
public function getTag()
{
return 'wrap';
}
}
Next, we need a compiler (a Node in the twig dialect), it will generate the PHP code associated with our {% wrap %} tag.
This tag is an alias of {{ macro_object.box(content) }}, so I wrote that line in a template and watched the resulting code in the resulting generated php file (stored in your app/cache/dev/twig directory). I got :
echo $this->getAttribute($this->getContext($context, "(macro object name)"), "(name)", array("(body)"), "method");
So my compiler became :
Twig/Node/WrapNode.php:
<?php
// src/Fuz/ToolsBundle/Twig/Node/WrapNode.php
namespace Fuz\ToolsBundle\Twig\Node;
class WrapNode extends \Twig_Node
{
public function __construct($object, $name, $body, $lineno = 0, $tag = null)
{
parent::__construct(array ('body' => $body), array ('object' => $object, 'name' => $name), $lineno, $tag);
}
public function compile(\Twig_Compiler $compiler)
{
$compiler
->addDebugInfo($this)
->write('ob_start();');
$compiler
->addDebugInfo($this)
->subcompile($this->getNode('body'));
if (is_null($this->getAttribute('object')))
{
$compiler
->write(sprintf('echo $this->get%s(ob_get_clean());', $this->getAttribute('name')) . "\n");
}
else
{
$compiler
->write('echo $this->getAttribute($this->getContext($context, ')
->repr($this->getAttribute('object'))
->raw('), ')
->repr($this->getAttribute('name'))
->raw(', array(ob_get_clean()), "method");')
->raw("\n");
}
}
}
Note : to know how work the subparsing / subcompiling, I read the spaceless extension source code.
That's all! We get an alias that let us use macros with a large body. To try it:
macros.html.twig:
{% macro box(content) %}
<div class="box indent">
<div class="padding">
{{ content | raw }} {# Don't forget the raw filter! #}
</div>
</div>
{% endmacro %}
some layout.html.twig:
{% import "FuzLayoutBundle:Default:macros.html.twig" as macros %}
{% wrap macros box %}
test
{% endwrap %}
{% macro test(content) %}
some {{ content | raw }} in the same file
{% endmacro %}
{% wrap test %}
macro
{% endwrap %}
Outputs:
<div class="box indent">
<div class="padding">
test
</div>
</div>
some macro in the same file
The wrapperheader, wrapperfooter, wrapper extension
This method is the one I tell you about in my question. You can read / implement it if you want to train yourself with token parsers, but functionnaly, that's less nice than the previous method.
In a wrapper.html.twig file, you declare all wrappers :
{% wrapperheader box %}
<div class="box">
{% endwrapper %}
{% wrapperfooter box %}
</div>
{% endwrapperfooter %}
In your features twig files, you use your wrappers :
{% wrapper box %}
This is my content
{% endwrapper %}
The following extension has 3 issues :
There is no way to store data (such as context variables) in the Twig Environnement. So when you define a {% wrapperheader NAME %}, you have basically no clean way to check if a header for NAME is already defined (in this extension, I use static properties).
When you include a twig file, it is parsed at runtime, not immediately (I mean, the included twig template is parsed while the generated file is executed, and not when the include tag is parsed). So that's not possible to know if a wrapper exists on a previousely included file when you parse the {% wrapper NAME %} tag. If your wrapper does not exist, this extension just displays what's between {% wrapper %} and {% endwrapper %} without any notice.
The idea of this extension is : when the parser meet a wrapperheader and wrapperfooter tag, the compiler store the content of the tag somewhere for a later use with the wrapper tag. But the twig context is passed to {% include %} as a copy, not by reference. So that's not possible to store the {% wrapperheader %} and {% wrapperfooter %} information inside that context, for an usage at upper level (in files that include files). I needed to use a global context too.
Here is the code, take care to change your namespaces.
First we need to create an extension that will add new token parsers to Twig.
Inside services.yml of a bundle, add the following lines to activate the extension :
parameters:
fuz_tools.twig.wrapper_extension.class: Fuz\ToolsBundle\Twig\Extension\WrapperExtension
services:
fuz_tools.twig.wrapper_extension:
class: '%fuz_tools.twig.wrapper_extension.class%'
tags:
- { name: twig.extension }
Inside your bundle, create a Twig directory.
Create the following Twig\Extension\WrapperExtension.php file :
<?php
// src/Fuz/ToolsBundle/Twig/Extension/WrapperExtension.php
namespace Fuz\ToolsBundle\Twig\Extension;
use Fuz\ToolsBundle\Twig\TokenParser\WrapperHeaderTokenParser;
use Fuz\ToolsBundle\Twig\TokenParser\WrapperFooterTokenParser;
use Fuz\ToolsBundle\Twig\TokenParser\WrapperTokenParser;
class WrapperExtension extends \Twig_Extension
{
public function getTokenParsers()
{
return array(
new WrapperHeaderTokenParser(),
new WrapperFooterTokenParser(),
new WrapperTokenParser(),
);
}
public function getName()
{
return 'wrapper';
}
}
Now we need to add the token parsers : our syntax is {% wrapper NAME %} ... {% endwrapper %} and the same with wrapperheader and wrapperfooter. So those token parsers are used to declare the tags, to retrive the wrapper's NAME, and to retrieve the body (what's between wrapper and endwrapper`).
The token parser for wrapper: Twig\TokenParser\WrapperTokenParser.php:
<?php
// src/Fuz/ToolsBundle/Twig/TokenParser/WrapperTokenParser.php
namespace Fuz\ToolsBundle\Twig\TokenParser;
use Fuz\ToolsBundle\Twig\Node\WrapperNode;
class WrapperTokenParser extends \Twig_TokenParser
{
public function parse(\Twig_Token $token)
{
$stream = $this->parser->getStream();
$name = $stream->expect(\Twig_Token::NAME_TYPE)->getValue();
$this->parser->getStream()->expect(\Twig_Token::BLOCK_END_TYPE);
$body = $this->parser->subparse(array($this, 'decideWrapperEnd'), true);
$this->parser->getStream()->expect(\Twig_Token::BLOCK_END_TYPE);
return new WrapperNode($name, $body, $token->getLine(), $this->getTag());
}
public function decideWrapperEnd(\Twig_Token $token)
{
return $token->test('endwrapper');
}
public function getTag()
{
return 'wrapper';
}
}
The token parser for wrapperheader: Twig\TokenParser\WrapperHeaderTokenParser.php:
<?php
// src/Fuz/ToolsBundle/Twig/TokenParser/WrapperHeaderTokenParser.php
namespace Fuz\ToolsBundle\Twig\TokenParser;
use Fuz\ToolsBundle\Twig\Node\WrapperHeaderNode;
class WrapperHeaderTokenParser extends \Twig_TokenParser
{
static public $wrappers = array ();
public function parse(\Twig_Token $token)
{
$lineno = $token->getLine();
$stream = $this->parser->getStream();
$name = $stream->expect(\Twig_Token::NAME_TYPE)->getValue();
if (in_array($name, self::$wrappers))
{
throw new \Twig_Error_Syntax("The wrapper '$name''s header has already been defined.", $lineno);
}
self::$wrappers[] = $name;
$this->parser->getStream()->expect(\Twig_Token::BLOCK_END_TYPE);
$body = $this->parser->subparse(array($this, 'decideWrapperHeaderEnd'), true);
$this->parser->getStream()->expect(\Twig_Token::BLOCK_END_TYPE);
return new WrapperHeaderNode($name, $body, $token->getLine(), $this->getTag());
}
public function decideWrapperHeaderEnd(\Twig_Token $token)
{
return $token->test('endwrapperheader');
}
public function getTag()
{
return 'wrapperheader';
}
}
The token parser for wrapperfooter: Twig\TokenParser\WrapperFooterTokenParser.php:
<?php
// src/Fuz/ToolsBundle/Twig/TokenParser/WrapperFooterTokenParser.php
namespace Fuz\ToolsBundle\Twig\TokenParser;
use Fuz\ToolsBundle\Twig\Node\WrapperFooterNode;
class WrapperFooterTokenParser extends \Twig_TokenParser
{
static public $wrappers = array ();
public function parse(\Twig_Token $token)
{
$lineno = $token->getLine();
$stream = $this->parser->getStream();
$name = $stream->expect(\Twig_Token::NAME_TYPE)->getValue();
if (in_array($name, self::$wrappers))
{
throw new \Twig_Error_Syntax("The wrapper '$name''s footer has already been defined.", $lineno);
}
self::$wrappers[] = $name;
$this->parser->getStream()->expect(\Twig_Token::BLOCK_END_TYPE);
$body = $this->parser->subparse(array($this, 'decideWrapperFooterEnd'), true);
$this->parser->getStream()->expect(\Twig_Token::BLOCK_END_TYPE);
return new WrapperFooterNode($name, $body, $token->getLine(), $this->getTag());
}
public function decideWrapperFooterEnd(\Twig_Token $token)
{
return $token->test('endwrapperfooter');
}
public function getTag()
{
return 'wrapperfooter';
}
}
The token parsers retrieve all the required information, we now need to compile those information into PHP. This PHP code will be generated by the twig engine inside a Twig_Template implementation (you can find generated classes in your cache directory). It generates code in a method, and the context of included files is not available (because the context array is not given by reference). In such a way, this is not possible to access what's inside the included file without a global context. That's why here, I use static attributes... That's not nice at all but I don't know how to avoid them (if you have ideas, please let me know! :)).
Compiler for the wrapper tag : Twig\Nodes\WrapperNode.php
<?php
// src/Fuz/ToolsBundle/Twig/Node/WrapperNode.php
namespace Fuz\ToolsBundle\Twig\Node;
class WrapperNode extends \Twig_Node
{
public function __construct($name, $body, $lineno = 0, $tag = null)
{
parent::__construct(array ('body' => $body), array ('name' => $name), $lineno, $tag);
}
public function compile(\Twig_Compiler $compiler)
{
$compiler
->addDebugInfo($this)
->write('if (isset(\\')
->raw(__NAMESPACE__)
->raw('\WrapperHeaderNode::$headers[')
->repr($this->getAttribute('name'))
->raw('])) {')
->raw("\n")
->indent()
->write('echo \\')
->raw(__NAMESPACE__)
->raw('\WrapperHeaderNode::$headers[')
->repr($this->getAttribute('name'))
->raw('];')
->raw("\n")
->outdent()
->write('}')
->raw("\n");
$compiler
->addDebugInfo($this)
->subcompile($this->getNode('body'));
$compiler
->addDebugInfo($this)
->write('if (isset(\\')
->raw(__NAMESPACE__)
->raw('\WrapperFooterNode::$footers[')
->repr($this->getAttribute('name'))
->raw('])) {')
->raw("\n")
->indent()
->write('echo \\')
->raw(__NAMESPACE__)
->raw('\WrapperFooterNode::$footers[')
->repr($this->getAttribute('name'))
->raw('];')
->raw("\n")
->outdent()
->write('}')
->raw("\n");
}
}
Compiler for the wrapperheader tag : Twig\Nodes\WrapperHeaderNode.php
<?php
// src/Fuz/ToolsBundle/Twig/Node/WrapperHeaderNode.php
namespace Fuz\ToolsBundle\Twig\Node;
/**
* #author alain tiemblo
*/
class WrapperHeaderNode extends \Twig_Node
{
static public $headers = array();
public function __construct($name, $body, $lineno = 0, $tag = null)
{
parent::__construct(array ('body' => $body), array ('name' => $name), $lineno, $tag);
}
public function compile(\Twig_Compiler $compiler)
{
$compiler
->write("ob_start();")
->raw("\n")
->subcompile($this->getNode('body'))
->write(__CLASS__)
->raw('::$headers[')
->repr($this->getAttribute('name'))
->raw('] = ob_get_clean();')
->raw("\n");
}
}
Compiler for the wrapperfooter tag : Twig\Nodes\WrapperFooterNode.php
<?php
// src/Fuz/ToolsBundle/Twig/Node/WrapperFooterNode.php
namespace Fuz\ToolsBundle\Twig\Node;
class WrapperFooterNode extends \Twig_Node
{
static public $footers = array();
public function __construct($name, $body, $lineno = 0, $tag = null)
{
parent::__construct(array ('body' => $body), array ('name' => $name), $lineno, $tag);
}
public function compile(\Twig_Compiler $compiler)
{
$compiler
->write("ob_start();")
->raw("\n")
->subcompile($this->getNode('body'))
->write(__CLASS__)
->raw('::$footers[')
->repr($this->getAttribute('name'))
->raw('] = ob_get_clean();')
->raw("\n");
}
}
The implementation is ok now. Let's try it!
Create a view named wrappers.html.twig :
{# src/Fuz/LayoutBundle/Resources/views/Default/wrappers.html.twig #}
{% wrapperheader demo %}
HEAD
{% endwrapperheader %}
{% wrapperfooter demo %}
FOOT
{% endwrapperfooter %}
Create a view named what you want.html.twig :
{# src/Fuz/HomeBundle/Resources/views/Default/index.html.twig #}
{% include 'FuzLayoutBundle:Default:wrappers.html.twig' %}
{% wrapper demo %}
O YEAH
{% endwrapper %}
This shows up :
HEAD O YEAH FOOT
There's a fairly straight forward method with Twig variables and macros.
<div class="box indent">
<div class="padding">
my code here
</div>
</div>
Create a macro:
{% macro box(content) %}
<div class="box indent">
<div class="padding">
{{ content }}
</div>
</div>
{% endmacro %}
And call it like this:
{% set content %}
my code here
{% endset %}
{{ _self.box(content) }}
Not particularly elegant but less mountains of code!
How i can wrap every block code with spaceless to crop whitespaces from my twig/html
for example now i have:
{% block content %}
<div class="box clearfix clearall">
<div class="ct colcontainer">
<div class="col-1">
<div class="chars">
<table class="layout data-char">
<thead>
blabla
{% endblock %}
And when symfony try to render it, i want that symfony saw
{% block content %}
{% spaceless %}
<div class="box clearfix clearall">
<div class="ct colcontainer">
<div class="col-1">
<div class="chars">
<table class="layout data-char">
<thead>
blabla
{% endspaceless %}
{% endblock %}
Define a custom Twig tag (the copy-and-paste way)
You can define a custom Twig tag spacelessblock which combines block and spaceless. Then you can use {% spacelessblock xyz %}…{% endspacelessblock %} in your templates. Here is how you do it the quick and dirty (copy and paste) way.
A new Twig node
First, define a class Twig_Node_SpacelessBlock (e.g. in the Extension directory of your bundle):
class Twig_Node_SpacelessBlock extends \Twig_Node_Block
{
public function __construct($name, Twig_NodeInterface $body, $lineno, $tag = null)
{
parent::__construct(array('body' => $body), array('name' => $name), $lineno, $tag);
}
public function compile(Twig_Compiler $compiler)
{
// top part of Block.compile
$compiler
->addDebugInfo($this)
->write(sprintf("public function block_%s(\$context, array \$blocks = array())\n", $this->getAttribute('name')), "{\n")
->indent()
;
// the content of the body is treated like in Spaceless.compile
$compiler
->write("ob_start();\n")
->subcompile($this->getNode('body'))
->write("echo trim(preg_replace('/>\s+</', '><', ob_get_clean()));\n")
;
// bottom part of Block.compile
$compiler
->outdent()
->write("}\n\n")
;
}
}
A new Twig token parser
Our new Twig node needs to be built somewhere whenever Twig finds a {% spacelessblock xyz %} in a template. For that, we need a token parser which we call Twig_TokenParser_SpacelessBlock. We basically copy and paste Twig_TokenParser_Block:
class Twig_TokenParser_SpacelessBlock extends \Twig_TokenParser
{
public function parse(Twig_Token $token)
{
// …
$this->parser->setBlock($name, $block = new Twig_Node_SpacelessBlock($name, new Twig_Node(array()), $lineno));
// …
}
public function decideBlockEnd(Twig_Token $token)
{
return $token->test('endspacelessblock');
}
public function getTag()
{
return 'spacelessblock';
}
}
Tell Twig about it
In your extension class:
class Extension extends \Twig_Extension
{
public function getTokenParsers()
{
return array(
new Twig_TokenParser_SpacelessBlock(),
);
}
}
Tell Symfony about it
If not already done, add the following to your your services.yml:
services:
# …
my.extension:
class: Acme\MyBundle\Extension\Extension
tags:
- { name: twig.extension }
Better alternatives
Preprocessor
A better way would be to use a preprocessor to simply replace
{% spacelessblock xyz %}
…
{% endspacelessblock %}
by
{% block xyz %}{% spaceless %}
…
{% endspaceless %}{% endblock %}
which reuses all the code that already has been written in the Twig project, including possible changes.
This is the code that gets executed (as displayed in "code behind this page" section):
Controller Code
/**
* #Route("/hello/{name}", name="_demo_hello")
* #Template()
*/
public function helloAction($name)
{
$name = "whatever";
$this->render('AcmeDemoBundle:Demo:hello.html.twig',
array('name' => '123'));
//return array('name' => 'abc');
}
Template Code
{% extends "AcmeDemoBundle::layout.html.twig" %}
{% block title "Hello " ~ name %}
{% block content %}
<h1>xHello {{ name }}!</h1>
{% endblock %}
The output is
xHello Raffael!
The URL: http://192.168.177.128/Symfony/web/app_dev.php/demo/hello/Raffael
And here is my problem:
When I uncomment the return within controller then "Raffael" is replaced with "abc" as expected.
But according to the Quicktour it is possible to determine the values of variables within the template via the render-Method.
To render a template in Symfony, use the render method from within a
controller and pass it any variables needed in the template:
$this->render('AcmeDemoBundle:Demo:hello.html.twig', array( 'name' =>
$name, ));
What's wrong?
Further down the quick tour implicitely reveales that you have to return the output of render:
public function helloAction($name)
{
return $this->render('AcmeDemoBundle:Demo:hello.html.twig',
array('name' => '123'));
}