搜索
首页后端开发php教程详解PHP EasyTpl的功能及安装使用方法

EasyTpl - 简单快速的 PHP 模板引擎

简单快速的 PHP 模板引擎。

功能特性

  • 简单、轻量且快速。
    • 无学习成本
    • 仅仅简单处理并转换为原生PHP语法
    • 兼容PHP原生语法使用
  • 更加简单的输出语法。 例如:{{= $var }} {{ $var }} {{ echo $var }}
  • 支持所有控制语法。 例如 if,elseif,else;foreach;for;switch
  • 支持链式访问数组值。 例如:{{ $arr.0 }} {{ $map.name }} {{ $map.user.name }}
  • 更加安全,默认会自动通过 htmlspecialchars 将输出结果进行处理
    • 除非设置了禁用或者手动使用 raw 过滤器
  • 支持使用PHP内置函数作为过滤器。 例如:{{ $var | ucfirst }}
  • 支持添加自定义过滤器
    • 默认内置过滤器:upper lower nl
  • 支持添加自定义指令,提供自定义功能
  • 支持模板中添加注释。 例如: {{# comments ... #}}

安装

  • 需要 PHP 8.0+

composer

composer require phppkg/easytpl

快速开始

use PhpPkg\EasyTpl\EasyTemplate;

$tplCode = <<<&#39;CODE&#39;
My name is {{ $name | strtoupper }},
My develop tags:

{{ foreach($tags as $tag) }}
- {{ $tag }}

{{ endforeach }}
CODE;

$t = new EasyTemplate();

$str = $t->renderString($tplCode, [
    &#39;name&#39; => &#39;inhere&#39;,
    &#39;tags&#39; => [&#39;php&#39;, &#39;go&#39;, &#39;java&#39;],
]);

echo $str;

渲染输出:

My name is INHERE,My develop tags:- php- go- java

更多使用说明

语法跟PHP原生模板一样的,加入的特殊语法只是为了让使用更加方便。

  • EasyTemplate 默认开启输出过滤,可用于渲染视图模板
  • TextTemplate 则是关闭了输出过滤,主要用于文本处理,代码生成等

配置设置

use PhpPkg\EasyTpl\EasyTemplate;$t = EasyTemplate::new([
    'tplDir' => 'path/to/templates',
    'allowExt' => ['.php', '.tpl'],]);// do something ...

更多设置:

/** @var PhpPkg\EasyTpl\EasyTemplate $t */
$t->disableEchoFilter();
$t->addFilter($name, $filterFn);
$t->addFilters([]);
$t->addDirective($name, $handler);

输出变量值

下面的语句一样,都可以用于打印输出变量值

{{ $name }}{{= $name }}{{ echo $name }}

更多:

{{ $name ?: 'inhere' }}{{ $age > 20 ? '20+' : '74a3835a50559319c970010127e40c0ddisableEchoFilter()
  • 模板中禁用输出过滤 {{ $name | raw }}
  • 快速访问数组值

    可以使用 . 来快速访问数组值。原来的写法也是可用的,简洁写法也会自动转换为原生写法。

    $arr = [
        'val0',
        'subKey' => 'val1',];

    在模板中使用:

    first value is: {{ $arr.0 }} // val0'subKey' value is: {{ $arr.subKey }} // val1

    If 语句块

    if 语句:

    {{ if ($name !== '') }}hi, my name is {{ $name }}{{ endif }}

    if else 语句:

    hi, my name is {{ $name }}age is {{ $age }}, and{{ if ($age >= 20) }}
     age >= 20.{{ else }}
     age 1151b160bdcc90f86856a2d25abad689= 50) }}
     age >= 50.{{ elseif ($age >= 20) }}
     age >= 20.{{ else }}
     age 2df235674a603143fda7a375e75eecf1 $tag) }}{{ $index }}. {{ $tag }}{{ endforeach }}

    模板中添加注释

    {{##}} 包裹的内容将会当做注释忽略。

    {{# comments ... #}}{{ $name }} // inhere

    multi lines:

    {{# this
     comments
     block
    #}}{{ $name }} // inhere

    使用过滤器

    默认内置过滤器:

    • upper - 等同于 strtoupper
    • lower - 等同于 strtolower
    • nl    - 追加换行符 \n

    过滤器使用示例

    您可以在任何模板中使用过滤器。

    基本使用:

    {{ 'inhere' | ucfirst }} // Inhere {{ 'inhere' | upper }} // INHERE

    链式使用:

    {{ 'inhere' | ucfirst | substr:0,2 }} // In{{ '1999-12-31' | date:'Y/m/d' }} // 1999/12/31

    传递非静态值:

    {{ $name | ucfirst | substr:0,1 }}{{ $user['name'] | ucfirst | substr:0,1 }}{{ $userObj->name | ucfirst | substr:0,1 }}{{ $userObj->getName() | ucfirst | substr:0,1 }}

    将变量作为过滤器参数传递:

    {{
        $suffix = '¥';}}{{ '12.75' | add_suffix:$suffix }} // 12.75¥

    自定义过滤器

    use PhpPkg\EasyTpl\EasyTemplate;$tpl = EasyTemplate::new();// use php built function$tpl->addFilter('upper', 'strtoupper');// 一次添加多个$tpl->addFilters([
        'last3chars' => function (string $str): string {
            return substr($str, -3);
        },]);

    在模板中使用:

    {{
      $name = 'inhere';}}{{ $name | upper }} // INHERE{{ $name | last3chars }} // ere{{ $name | last3chars | upper }} // ERE

    自定义指令

    您可以使用指令实现一些特殊的逻辑。

    $tpl = EasyTemplate::new();$tpl->addDirective(
        'include',
        function (string $body, string $name) {
            /** will call {@see EasyTemplate::include()} */
            return '$this->' . $name . $body;
        });

    在模板中使用:

    {{ include('part/header.tpl', ['title' => 'My world']) }}

    Github: github.com/phppkg/easytpl

     推荐学习:《PHP视频教程》                                                

    以上是详解PHP EasyTpl的功能及安装使用方法的详细内容。更多信息请关注PHP中文网其他相关文章!

    声明
    本文转载于:learnku。如有侵权,请联系admin@php.cn删除
    PHP依赖注入容器:快速启动PHP依赖注入容器:快速启动May 13, 2025 am 12:11 AM

    aphpdepentioncontiveContainerIsatoolThatManagesClassDeptions,增强codemodocultion,可验证性和Maintainability.itactsasaceCentralHubForeatingingIndections,因此reducingTightCightTightCoupOulplingIndeSingantInting。

    PHP中的依赖注入与服务定位器PHP中的依赖注入与服务定位器May 13, 2025 am 12:10 AM

    选择DependencyInjection(DI)用于大型应用,ServiceLocator适合小型项目或原型。1)DI通过构造函数注入依赖,提高代码的测试性和模块化。2)ServiceLocator通过中心注册获取服务,方便但可能导致代码耦合度增加。

    PHP性能优化策略。PHP性能优化策略。May 13, 2025 am 12:06 AM

    phpapplicationscanbeoptimizedForsPeedAndeffificeby:1)启用cacheInphp.ini,2)使用preparedStatatementSwithPdoforDatabasequesies,3)3)替换loopswitharray_filtaray_filteraray_maparray_mapfordataprocrocessing,4)conformentnginxasaseproxy,5)

    PHP电子邮件验证:确保正确发送电子邮件PHP电子邮件验证:确保正确发送电子邮件May 13, 2025 am 12:06 AM

    phpemailvalidation invoLvesthreesteps:1)格式化进行regulareXpressecthemailFormat; 2)dnsvalidationtoshethedomainhasavalidmxrecord; 3)

    如何使PHP应用程序更快如何使PHP应用程序更快May 12, 2025 am 12:12 AM

    tomakephpapplicationsfaster,关注台词:1)useopcodeCachingLikeLikeLikeLikeLikePachetoStorePreciledScompiledScriptbyTecode.2)MinimimiedAtabaseSqueriSegrieSqueriSegeriSybysequeryCachingandeffeftExting.3)Leveragephp7 leveragephp7 leveragephp7 leveragephpphp7功能forbettercodeefficy.4)

    PHP性能优化清单:立即提高速度PHP性能优化清单:立即提高速度May 12, 2025 am 12:07 AM

    到ImprovephPapplicationspeed,关注台词:1)启用opcodeCachingwithapCutoredUcescriptexecutiontime.2)实现databasequerycachingusingpdotominiminimizedatabasehits.3)usehttp/2tomultiplexrequlexrequestsandredececonnection.4 limitsclection.4.4

    PHP依赖注入:提高代码可检验性PHP依赖注入:提高代码可检验性May 12, 2025 am 12:03 AM

    依赖注入(DI)通过显式传递依赖关系,显着提升了PHP代码的可测试性。 1)DI解耦类与具体实现,使测试和维护更灵活。 2)三种类型中,构造函数注入明确表达依赖,保持状态一致。 3)使用DI容器管理复杂依赖,提升代码质量和开发效率。

    PHP性能优化:数据库查询优化PHP性能优化:数据库查询优化May 12, 2025 am 12:02 AM

    databasequeryOptimizationinphpinvolVolVOLVESEVERSEVERSTRATEMIESOENHANCEPERANCE.1)SELECTONLYNLYNESSERSAYCOLUMNSTORMONTOUMTOUNSOUDSATATATATATATATATATATRANSFER.3)

    See all articles

    热AI工具

    Undresser.AI Undress

    Undresser.AI Undress

    人工智能驱动的应用程序,用于创建逼真的裸体照片

    AI Clothes Remover

    AI Clothes Remover

    用于从照片中去除衣服的在线人工智能工具。

    Undress AI Tool

    Undress AI Tool

    免费脱衣服图片

    Clothoff.io

    Clothoff.io

    AI脱衣机

    Video Face Swap

    Video Face Swap

    使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

    热门文章

    热工具

    EditPlus 中文破解版

    EditPlus 中文破解版

    体积小,语法高亮,不支持代码提示功能

    PhpStorm Mac 版本

    PhpStorm Mac 版本

    最新(2018.2.1 )专业的PHP集成开发工具

    SublimeText3 Linux新版

    SublimeText3 Linux新版

    SublimeText3 Linux最新版

    WebStorm Mac版

    WebStorm Mac版

    好用的JavaScript开发工具

    ZendStudio 13.5.1 Mac

    ZendStudio 13.5.1 Mac

    功能强大的PHP集成开发环境