lordsimal/custom-html-elements

允许您创建自定义HTML元素来渲染更复杂的模板部分

0.2.1 2024-08-13 14:44 UTC

This package is auto-updated.

Last update: 2024-09-01 08:04:58 UTC


README

Latest Stable Version Total Downloads Latest Unstable Version License PHP Version Requirecodecov

允许您通过更简单的HTML表示来创建自定义HTML元素,以渲染更复杂的模板部分

要求

  • PHP 8.1+

安装

composer require lordsimal/custom-html-elements

使用

这是您想要使用的自定义HTML元素的一个示例表示

<c-youtube src="RLdsCL4RDf8"/>

因此,这将像这样出现在HTML输出中

<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Example Page</title>
    <meta name="author" content="Kevin Pfeifer">
</head>
<body> 
    <c-youtube src="RLdsCL4RDf8"/>
</body>
</html>

要渲染此自定义HTML元素,您需要这样做

$htmlOutput = ''; // This variable represents what is shown above
$engine = new \LordSimal\CustomHtmlElements\TagEngine([
    'tag_directories' => [
        __DIR__.DIRECTORY_SEPARATOR.'Tags'.DIRECTORY_SEPARATOR,
        __DIR__.DIRECTORY_SEPARATOR.'OtherTagsFolder'.DIRECTORY_SEPARATOR,
    ],
]);
echo $engine->parse($htmlOutput);

元素逻辑可以放在例如 Tags/Youtube.phpOtherTagsFolder/Youtube.php

<?php
namespace App\Tags;

use LordSimal\CustomHtmlElements\CustomTag;

class Youtube extends CustomTag 
{
    public static string $tag = 'c-youtube';

    public function render(): string
    {
        return <<< HTML
        <iframe width="560" height="315" 
            src="https://www.youtube.com/embed/{$this->src}" 
            allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" 
            allowfullscreen>
        </iframe>
HTML;
    }
}

如您所见,主要分为两部分

public static string $tag = 'c-youtube';

它定义了这个类代表什么HTML标签,以及 render() 方法。

render() 方法内部,您可以访问传递给元素的所有HTML属性。

因此,例如

<c-button type="primary" text="Click me" url="/something/stupid" />

将通过

class Button extends CustomTag
{
    public static string $tag = 'c-button';

    public function render(): string
    {
        $classes = ['c-button'];
        if ($this->type == 'primary') {
            $classes[] = 'c-button--primary';
        }
        $classes = implode(' ', $classes);
        return <<< HTML
            <a href="$this->url" class="$classes">$this->text</a>
HTML;
    }
}

访问内部内容

您可能想创建自定义HTML元素,例如

<c-github>Inner Content</c-github>

要访问类内部 Inner Content 的文本,您只需像这样调用 $this->innerContent

class Github extends CustomTag
{
    public static string $tag = 'c-github';

    public function render(): string
    {
        return <<< HTML
            $this->innerContent
HTML;
    }
}

自闭合元素

默认情况下,每个自定义HTML元素都可以这样使用

<c-youtube src="RLdsCL4RDf8"></c-youtube>

或者

<c-youtube src="RLdsCL4RDf8" />

两种方式都会以相同的方式渲染。

渲染嵌套自定义HTML元素

默认情况下,这个库会渲染嵌套自定义HTML元素。所以您不需要担心这个问题。

禁用自定义HTML元素

您有两种方法可以禁用自定义HTML元素

禁用所有自定义HTML元素的出现

您可以在自定义HTML元素类中添加属性

public bool $disabled = true;

仅禁用特定自定义HTML元素的出现

您可以添加属性 disabled,然后它将不会被渲染。

<c-youtube src="RLdsCL4RDf8" disabled />

更多示例?

查看所有不同的TagEngine 测试

致谢

这个库受到了以下包的启发