blablacar/twig-stamp

此包已被弃用,不再维护。未建议替代包。

在基础模板中放置一个戳记占位符,从任何地方填充它。

dev-master 2018-03-29 14:54 UTC

This package is not auto-updated.

Last update: 2023-12-27 11:24:26 UTC


README

在基础模板中放置一个占位符,从任何地方填充它。

想法

我们的前端同事需要在我们基础布局中插入SVG精灵,但不希望插入所有图标:只插入整个页面中实际使用的SVG,按需。问题是我们的页面很复杂,有很多 {% include %}{% render %} 和其他功能,这使得我们难以轻松跟踪所需的SVG图标并在基础布局的顶部插入它们。

这个Twig扩展增加了在基础布局的某个位置放置占位符的能力,并可以从任何页面(无论其范围和独立性如何)中放置内容。

示例

为了简化,假设我们想创建一个页面,顶部有一个基于页面内容的目录(toc)。

主要布局

{# demo.twig #}
{% stamp 'toc' %}

{# here is the placeholder where we want the table of contents dumped #}
{% stamp_dump 'toc' %}

{{ include('section1.twig') }}
{# ... #}

{% endstamp %}

一个部分

{# section1.twig #}
{# Here, we add a stamp that will be dumped in the placeholder later on #}
<h1>{{ stamp_use('toc', 'Section 1') }}</h1>

Lorem ipsum dolor sit amet, eu vel aliquam adversarium...

目录

{# toc.twig #}
<h1>Table of contents</h1>

<ul>
    {% for title in list %}
        <li>{{ title }}</li>
    {% endfor %}
</ul>

现在我们需要创建逻辑

<?php

namespace Demo\TableOfContents;

use Blablacar\Twig\Api\StampInterface;

class TableOfContentsStamp implements StampInterface
{
    protected $twig;
    protected $list = [];

    public function __construct(\Twig_Environment $twig)
    {
        $this->twig = $twig;
    }

    /**
     * Method called with {{ stamp_use('toc', 'Section 1') }}
     */
    public function useStamp()
    {
        list($title) = func_get_args();
        $this->list[] = $title;

        return $title;
    }

    /**
     * Method called when reaching {% endstamp %}, that will dump content in the {% stamp_dump %} placeholder
     */
    public function dumpStamp()
    {
        return $this->twig->render('toc.twig', [
            'list' => $this->list
        ]);
    }

    public function getName()
    {
        return 'toc';
    }
}

我们需要在扩展中注册戳记

use Blablacar\Twig\Extension\StampExtension;
// ...

$extension = new StampExtension();
$twig->addExtension($extension);

$stamp = new TableOfContentsStamp($twig);
$extension->addStamp($stamp);

运行此示例,您将得到

<h1>Table of contents</h1>

<ul>
    <li>Section 1</li>
</ul>

<h1>Section 1</h1>

Lorem ipsum dolor sit amet, eu vel aliquam adversarium...

安装

composer require blablacar/twig-stamp

许可证

MIT许可证(MIT)

请阅读LICENSE文件以获取更多详细信息。