setono / tag-bag
以编程方式注入动态标签
v2.3.0
2024-05-21 09:28 UTC
Requires
- php: >=8.1
- ext-hash: *
- psr/event-dispatcher: ^1.0
- psr/log: ^1.1 || ^2.0 || ^3.0
- webmozart/assert: ^1.11
Requires (Dev)
- infection/infection: ^0.26.21
- phpunit/phpunit: ^10.5.20
- psalm/plugin-phpunit: ^0.19
- setono/code-quality-pack: ^2.7
README
标签袋是一种面向对象且可扩展性很强的添加内容/标签到您页面上的方式。
标签袋的一个非常常见的用例是跟踪您页面上的事件。
安装
composer require setono/tag-bag
基本用法
<?php declare(strict_types=1); use Setono\TagBag\Renderer\ElementRenderer; use Setono\TagBag\Tag\InlineScriptTag; use Setono\TagBag\TagBag; $tagBag = new TagBag(); // in a controller or service $tagBag->add(InlineScriptTag::create('trackSomething();')); // in your template $tagBag->renderAll();
上述调用TagBagInterface::renderAll()
将输出以下内容
<script>trackSomething();</script>
这里我们介绍了标签袋的两大重要概念:标签和标签的渲染。
标签是实现了TagInterface
的PHP类,它们旨在使您更容易在页面上输出内容。其中包含的是一些非常基础的标签,您可能会发现您想要使用一些更高级的标签,您可以在下面的标签部分中了解更多。
标签
基础库包括以下标签
内容标签
<?php use Setono\TagBag\Tag\ContentTag; $tag = ContentTag::create('<div class="class-name">tag</div>');
渲染为
<div class="class-name">tag</div>
元素标签
<?php use Setono\TagBag\Tag\ElementTag; $tag = ElementTag::createWithContent('div', 'content');
渲染为
<div>content</div>
内联脚本标签
<?php use Setono\TagBag\Tag\InlineScriptTag; $tag = InlineScriptTag::create('alert("Hey!");');
渲染为
<script> alert("Hey!"); </script>
您还可以向内联脚本标签添加属性
<?php use Setono\TagBag\Tag\InlineScriptTag; $tag = InlineScriptTag::create('{"@context": "https://schema.org/"}')->withType('application/ld+json');
以上内容渲染为
<script type="application/ld+json"> {"@context": "https://schema.org/"} </script>
链接标签
<?php use Setono\TagBag\Tag\LinkTag; $tag = LinkTag::create('stylesheet', 'https://example.com/style.css');
渲染为
<link rel="stylesheet" href="https://example.com/style.css">
样式标签
<?php use Setono\TagBag\Tag\StyleTag; $tag = StyleTag::create('body { background-color: red; }');
渲染为
<style> body { background-color: red; } </style>
Twig 标签
使用Twig模板进行渲染。请参阅安装说明和用法此处。
PHP 模板标签
Gtag 标签
如果您正在使用Google的服务,其中一些服务允许您使用gtag来跟踪事件。
为了更容易地创建这些标签,您可以使用标签袋的gtag扩展。
渲染器
基础库包含两个渲染器。渲染器实现了RendererInterface
。
就像标签一样,子包中也有渲染器。
内容渲染器
ContentRenderer
渲染您在标签中输入的内容。
元素渲染器
ElementRenderer
渲染“元素标签”,例如<script>
、<style>
、<meta>
、<link>
,基本上是所有基于HTML元素的标签。
存储
标签袋的预期用途是在请求结束时保存标签袋,并在开始请求生命周期时恢复它。《TagBagInterface》有用于这些事件的store
和restore
方法。
<?php use Setono\TagBag\Tag\InlineScriptTag; use Setono\TagBag\TagBagInterface; /** @var TagBagInterface $tagBag */ // in a controller or service $tagBag->add(new InlineScriptTag('trackSomething();')); // this stores the contents of the tag bag $tagBag->store(); // this restores the contents of the tag bag $tagBag->restore();
框架集成
- Symfony: TagBagBundle