树枝移除断线

问题描述 投票:0回答:2

所以我有以下代码:

{{ use('frontend/assets/AppAsset')}}
{{ register_app_asset() }}
{{ this.beginPage() }}
<!doctype html>
<html lang="{{app.language}}">
<head>

但是在编译后的 html 文件中,我在

<!doctype html>
之前看到了 3 个空行。我怎样才能解决这个问题?使用
{% spaceless %} {% endspaceless %}
会产生 2 个空行。

twig
2个回答
2
投票

您可以通过在标签中添加 空白控制修饰符(连字符)来修剪空白 - 请参阅文档中的空白控制部分

例如:

{{- use('frontend/assets/AppAsset')}}
{{ register_app_asset() }}
{{ this.beginPage() -}}
<!doctype html>
<html lang="{{app.language}}">
<head>

0
投票

更好地实现自己的过滤器,例如无空间但具有自己的逻辑:

创建类或添加所有树枝过滤器/函数的存储位置 类 CustomTwigExtension:


use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;

class CustomTwigExtension extends AbstractExtension
{
   public function getFilters()
   {
       return [
           new TwigFilter('emptyLineLess', [$this, 'emptyLineLess']),
       ];
   }

   public function emptyLineLess($text)
   {
       // Replace multiple consecutive empty lines with just one
       return preg_replace("/\n\s*\n/", "\n", $text);
   }
}

在装载机中:

$loader = new \Twig\Loader\FilesystemLoader('/path/to/template');
$twig = new \Twig\Environment($loader, [
    'cache' => '/path/to/cache', // Adjust for your project
    // Other Twig environment configurations
]);

$twig->addExtension(new CustomTwigExtension());

.twig 中的用法:


{% filter emptyLineLess %}
    Line 1

    Line 2


    Line 3
{% endfilter %}
© www.soinside.com 2019 - 2024. All rights reserved.