如何用无空间来包装每个块代码以从我的twig / html中裁剪空白
例如现在我有:
{% 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 %}
当symfony尝试渲染它时,我希望symfony看到
{% 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 %}
答案 0 :(得分:5)
您可以定义结合block
和spaceless
的自定义Twig标记spacelessblock
。然后,您可以在模板中使用{% spacelessblock xyz %}…{% endspacelessblock %}
。以下是快速和脏(复制和粘贴)方式的方法。
首先,定义一个类Twig_Node_SpacelessBlock
(例如,在您的包的Extension
目录中):
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")
;
}
}
每当Twig在模板中找到{% spacelessblock xyz %}
时,我们需要在某处构建新的Twig节点。为此,我们需要一个令牌解析器,我们称之为Twig_TokenParser_SpacelessBlock
。我们基本上复制并粘贴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';
}
}
在您的分机课程中:
class Extension extends \Twig_Extension
{
public function getTokenParsers()
{
return array(
new Twig_TokenParser_SpacelessBlock(),
);
}
}
如果尚未完成,请将以下内容添加到您的services.yml
:
services:
# …
my.extension:
class: Acme\MyBundle\Extension\Extension
tags:
- { name: twig.extension }
更好的方法是使用预处理器来简单地替换
{% spacelessblock xyz %}
…
{% endspacelessblock %}
通过
{% block xyz %}{% spaceless %}
…
{% endspaceless %}{% endblock %}
它重用了已经在Twig项目中编写的所有代码,包括可能的更改。