lmc/twigx-bundle

这是一个扩展Twig模板引擎的Symfony扩展包,支持类似JSX的语法。

安装次数: 30,453

依赖项: 1

建议者: 0

安全: 0

星标: 10

关注者: 10

分支: 0

公开问题: 2

类型:symfony-bundle

3.3.0 2024-06-12 11:14 UTC

This package is auto-updated.

Last update: 2024-09-12 11:52:02 UTC


README

Latest Stable Version Coverage Status

通过类似JSX的标记扩展Symfony的Twig模板引擎。

要求

  • PHP 7.4 或 8.1
  • Symfony 4.4+ 或 5.4+ 或 ^6.1
  • Twig >=1.44.6 或 >=2.12.5 或 3+

变更日志

查看 CHANGELOG

如何安装

步骤 1

使用 composer 下载

安装包

composer require lmc/twigx-bundle

步骤 2

TwigXBundle 添加到包中(在 all 包下)。如果你使用Symfony flex,它将自动配置。

bundles.php

    return [
        ...,
        Lmc\TwigXBundle\TwigXBundle::class => ['all' => true],
    ];

步骤 3(可选)

如果你想更改默认设置,创建一个配置文件

config/packages/twigx.yml

    # all parameters are optional
    twigx:
        # define one or more paths to expand or overload components (uses glob patterns)
        paths:
            - "%kernel.project_dir%/templates/components"
        paths_alias: 'jobs-ui' # alias for twig paths above (default is 'spirit')

使用方法

现在你可以在Symfony项目中使用具有类似HTML语法的Twig组件。你只需要记住,与HTML不同,组件标签必须始终以大写字母开头

<ComponentName attr="value">Some other content</ComponentName>
  ...
<ComponentName attr="value" />

你可以这样传递属性

<ComponentName
:any="'any' ~ 'prop'" // this return as "any" prop with value "anyprop"
other="{{'this' ~ 'works' ~ 'too'}}"
anotherProp="or this still work"
not-this="{{'this' ~ 'does'}}{{ 'not work' }}" // this returns syntax as plain text but prop with dash work
ifCondition="{{ variable == 'success' ? 'true' : 'false' }}"  // condition can only be written via the ternary operator
jsXCondition={ variable == 'success' ? 'true' : 'false' }  // condition can only be written via the ternary operator
isBoolean={false}  // if value is false
numberValue={11}  // if value is number 11
isOpen  // if no value is defined, it is set to true
>
    Submit
</ComponentName>

或者纯原始实现

{% embed "@spirit/componentName.twig" with { props: {
    attr: 'value'
}} %}
    {% block content %}
        Some other content
    {% endblock %}
{% endembed %}

允许的括号

你可以使用两种语法将变量传递给props。类似JSX的语法使用单个 {...} 括号,或者类似Twig的语法使用 {{...}} 括号。在这两种情况下,都可以在值周围有空白。请参见下面的示例。

类似JSX的语法示例

<ComponentName variable={value} anotherVariable={ value } />

类似Twig的语法示例

<ComponentName variable={{value}} anotherVariable={{ value }} />

如果你想要扩展这些组件,一个示例指南在这里 这里。如果你想要贡献,请阅读指南 这里