cf-git / twig-once
Twig template tag {% once [name] %}{% endonce %}
1.0.7
2023-12-16 12:39 UTC
Requires
- php: >7.2
- twig/twig: > 3.0
README
MicroExtension for Twig template library. Can be used when need restrict once some part of code.
twig/twig
library is required.
How to use.
1.Require this extension with your composer
composer require cf-git/twig-once
2.include autoload file in your php project (if it not included);
include_once('vendor/autoload.php');
3.add token parser to Twig\Environment
$twig = new \Twig\Environment($loader, $config); $twig->addExtension(new \CFGit\TwigEngine\Extensions\Once\OnceExtension())
or like this
$twig = new \Twig\Environment($loader, $config); $twig->addTokenParser(new \CFGit\TwigEngine\Extensions\Once\OnceTokenParser());
4.Then use twig documentation!
And use it.
If you do right. You gets some like this.
{{-- Main content --}} {% for i in range(0, 5) %} <div>{{ i }}</div> {% once hello %} <script>console.log("[{{ i }}]Hello world!")</script> {% endonce %} {% endfor %}
outputs
<div>0</div> <script>console.log("[0] Hello world!")</script> <div>1</div> <div>2</div> <div>3</div> <div>4</div> <div>5</div>
Same with included files
{{-- Main content --}} {% for i in range(0,5) %} {% include "x.twig" with({(i): i}) %} {% endfor %}
{{-- x.twig content --}} <!-- {{ i }} --> {% once %} <!-- [{{ i }}] Hello world! --> {% endonce %}
outputs
<!-- 0 --> <!-- [0] Hello world! --> <!-- 1 --> <!-- 2 --> <!-- 3 --> <!-- 4 --> <!-- 5 -->