mercator / wn-twigext-plugin
Winter CMS Twig 扩展插件
Requires
- php: >=8.0
- composer/installers: ~1.0
- siniliote-twig/date-extra: ^3.4
- twig/cache-extra: ^3
- twig/cssinliner-extra: ^3.3
- twig/extra-bundle: 3.x-dev
- twig/html-extra: 3.x-dev
- twig/inky-extra: ^3
- twig/intl-extra: 3.x-dev
- twig/markdown-extra: ^3
- twig/string-extra: ^3
README
TwigExt 为 WinterCMS 提供了一组 Twig 过滤器和函数。此外,它允许开发者轻松地将新的 Twig 函数和过滤器添加到 WinterCMS 主题。
该插件基于 Vojta Svoboda 的 OctoberCMS Twig 扩展,并包含该功能。它已在 WinterCMS 1.1.7 上进行过测试。
安装
使用 Composer 安装插件,执行以下命令
composer require mercator/wn-twigext-plugin
从您的 WinterCMS 安装根目录执行。
或者,创建一个名为 "mercator/twigext" 的目录,从 Github 下载 文件 并将它们移动到新创建的子目录中。
一旦 WinterCMS 市场可用,将添加从 WinterCMS 后端安装的功能。
现在您可以在主题(布局、部分等)中使用新添加的过滤器和函数。例如
{% redirect('https://mercator.li') %}
或者
{% redirect('/contact') %}
或者
This is just {{ 'great' | uppercase }}
可用函数
二维码
用于内联使用的二维码(qrcodeSRC 和 qrcodeIMG)
创建一个在透明背景上指向 mercator.li 的红色二维码的 GIF
<img alt="mercator dot li" src="{{ qrcodeSRC("https://mercator.li", 2, "XXXXXX", "000000") }}">
或者,使用简短版本
{{ qrcodeIMG("https://mercator.li", 2, "XXXXXX", "FF0000") }}
以生成完整的图像标签,即
<img alt="https://mercator.li" src="{{ qrcodeSRC("https://mercator.li", 2, "XXXXXX", "FF0000") }}">
在这种情况下,alt 将与实际的二维码内容相同。
您可以创建所有不同类型的二维码,例如 vcard
{{ qrcodeIMG("
BEGIN:VCARD
VERSION:2.1
FN:Max Mustermann
N:Mustermann;Max
TITLE:Dr.sc.techn.
TEL;CELL:+41 23 456 78 90
TEL;WORK;VOICE:+41 44 123 45 67
TEL;HOME;VOICE:+41 43 123 45 67
EMAIL;HOME;INTERNET:max.mustermann@musterorg.com
EMAIL;WORK;INTERNET:max.mustermann.private@mustermax.ch
URL:http://musterorg.com
ADR:;;Haputplatz 1;Kussnacht am Rigi;SZ;6403;Schweiz
ORG: Musterorg
END:VCARD
", 4) }}
上述函数的参数如下
- text: 要转换为二维码的文本,例如 https://mercator.li。默认为 "此处无数据"。
- scale: 二维码的缩放因子,1 是最小的。默认为 2。
- background: 背景颜色,以 RGB 十六进制格式。设置为 XXXXXX 以生成透明背景。默认为 XXXXXX,即透明。
- foreground: 前景颜色,以 RGB 十六进制格式。默认为 000000,即黑色。
- ecc: 错误纠正级别,有效值:qr, qr-l, qr-m, qr-q, qr-h。默认为 qr-l。
存储
目录
- storageDirectories(directory, [disk="local"]) --> 返回 directory 上的相应 disk 的目录数组
- storageAllDirectories(directory, [disk="local"]) --> 返回 directory 及其子目录上的相应 disk 的目录数组
- storageDeleteDirectory(directory, [disk="local"]) 删除相应 disk 上的 directory
- storageFiles(directory, [disk="local"]) --> 返回相应 disk 上 directory 中的文件数组。结果不包括目录。
- storageAllFiles(directory, [disk="local"]) --> 返回相应 disk 上 directory 及其子目录中的文件数组。结果不包括目录。
文件
- storageExists(file,[disk="local"]) 返回 true/false:检查相应 disk 上的 file 是否存在
- storageGet(file,[disk="local"]) 返回相应磁盘上的 file 内容
- storageSize(file,[disk="local"]) 返回相应磁盘上的 file 大小
- storageLastModified(file,[disk="local"]) 返回相应磁盘上的 file 最后修改日期
- storagePut(file, content,[disk="local"]) 将 content 写入相应磁盘上的 file
- storageCopy(from, to, [disk="local"]) 复制文件
- storageMove(from, to, [disk="local"]) 移动文件
- storagePrepend(file, content,[disk="local"]) 在相应磁盘上的 file 前面添加 content
- storageAppend(file, content,[disk="local"]) 在相应磁盘上的 file 后面添加 content
- storageDelete(file,[disk="local"]) 删除相应磁盘上的 file
地理编码
为给定的街道地址提供地理坐标(经度和纬度)。用法
{% set geo = geocodeAddress("Pardeplatz, Zurich, Switzerland) %}
The address is located at {{ geo.longitude }} {{ geo.latitude }} (long/lat).
密码学
将 Laravel 的加密功能 作为 Twig 函数提供
- cryptEncryptString(value) 实现 Crypt::encryptString
- cryptDecryptString(vakue) 实现 Crypt::decryptString
- cryptEncrypt(value) 实现 Crypt::encrypt
- cryptDecrypt(vakue) 实现 Crypt::decrypt
Cookie
将 Laravel 的 Cookie 功能 作为 Twig 函数提供
- cookieQueue(key, [value = true], [duration in seconds = 86400])
- cookieForever(key, [value = true])
- cookieGet(key)
- cookieExpire(key)
例如,使用 Cookie 来(重新)显示文本,例如每天一次(86400 秒后)
{% set key = ("cookie-key" %}
{% set updated = (element.published | strftime('%Y-%m-%d-%H-%M-%S')) %}
{% if (not cookieGet(key)) or (cookieGet(key) < updated) %}
Hello, this is the text you want to display once a day (every 86400 seconds)
{% endif %}
{{ cookieQueue(key, updated, 86400) }}
缓存
将 Laravel 的缓存功能 作为 Twig 函数提供
- cacheAdd(key, value, [duration=3600 seconds]) 实现 Cache::Add
- cachePut(key, value, [duration=3600 seconds]) 实现 Cache::Put
- cacheForever(key) 实现 Cache::Forever
- cacheForget(key) 实现 Cache::Forget
- cacheFlush() 实现 Cache::Flush
- cacheGet(key, [default value if not found = null]) 实现 Cache::Get
- cacheIncrement(key, [default increment value = 1]) 实现 Cache::Increment
- cacheDecrement(key, [default decrement value = 1]) 实现 Cache::Increment
- cachePull(key, default value if not found = null]) 实现 Cache::Pull
会话
将 Laravel 的会话功能 作为 Twig 函数提供
- sessionPush(key, value)
- sessionGet(key, [default vaklue when key is not found = ""]) --> value
- sessionPull(key, [default vaklue when key is not found = ""]) --> value
- sessionHas(key)
- sessionForget(key)
- sessionFlush()
- sessionRegenerate()
- sessionFlash(key, value)
- sessionReflash()
路径
将 Winter 的路径辅助功能作为 Twig 函数提供
- pathBase([file = ""]) --> 相对于 Winter 根目录的给定文件的完全合格路径
- pathConfig([file = ""]) --> 相对于配置目录的给定文件的完全合格路径
- pathDatabase([file = ""]) --> 相对于配置目录的给定文件的完全合格路径
- pathMedia([file = ""]) --> 相对于媒体目录的给定文件的完全合格路径
- pathPlugins([file = ""]) --> 相对于插件目录的给定文件的完全合格路径
- pathPublic([file = ""]) --> 相对于公共目录的给定文件的完全合格路径
- pathStorage([file = ""]) --> 相对于存储目录的给定文件的完全合格路径
- pathTemp([file = ""]) --> 相对于临时目录的给定文件的完全合格路径
- pathThemes([file = ""]) --> 相对于主题目录的给定文件的完全合格路径
- pathUpload([file = ""]) --> 相对于上传目录的给定文件的完全限定路径
preg_grep
提供模式匹配功能。
preg_grep(array of strings, pattern, [flags = 0]) 接收一个字符串数组,并返回一个只包含与给定 pattern 匹配的输入元素的数组,有关详细信息,请参阅相应的 PHP 函数 preg_grep。
用于识别所有 GIF、JP(E)G 和 TIF(F) 文件的示例模式:"/(\.+)(?i:png|jpg|jpeg|gif|tiff|tif)/"
通信
telegram
telegram (message, [botID=null], [chatID=null]) 使用指定的 chat 向 Telegram ChatBot 发送消息。如果未定义 ChatBot ID 和 chat ID,则使用后端定义的默认值。与 BOT Father 交谈以创建 ChatBotID 和相应的 chat。
mailRawTo
mailRawTo(message, [recipient]) 将 message 发送到指定的 recipient。如果没有指定接收者,则使用后端设置中定义的默认接收者。
redirect
重定向到特定 URL
{% redirect('https://mercator.li') %}
或者
{% redirect('/contact') %}
config
函数将 Laravel config()
辅助函数的功能移动到 Twig。
{{ config('app.locale') }}
示例将输出当前存储在 app.locale
中的值。有关 Laravel 配置辅助函数的更多信息,请参阅此处。
env
函数将 Laravel env()
辅助函数的功能移动到 Twig。
{{ env('APP_ENV', 'production') }}
示例将输出当前存储在 APP_ENV
环境变量中的值。第二个参数是默认值,当 ENV 键不存在时使用。
session
函数将 Laravel session()
辅助函数的功能移动到 Twig。
{{ session('my.session.key') }}
示例将输出当前存储在 my.session.key
中的值。有关 Laravel 会话辅助函数的更多信息,请参阅此处。
请注意,还提供了额外的会话功能,请参阅以下内容。
trans
函数将 Laravel trans()
辅助函数的功能移动到 Twig。
{{ trans('acme.blog::lang.app.name') }}
示例将输出存储在虚构博客插件本地化文件中的值。有关 Winter CMS 中本地化的更多信息,请参阅此处。
var_dump
输出有关变量的信息。也可以用作过滤器。
<pre>{{ var_dump(users) }}</pre>
template_from_string
函数从字符串加载模板。
{% set name = 'John' %}
{{ include(template_from_string("Hello {{ name }}")) }}
{{ include(template_from_string("Hurry up it is: {{ "now"|date("m/d/Y") }}")) }}
可用过滤器
strftime, uppercase, lowercase, ucfirst, lcfirst, ltrim, rtrim, str_repeat, plural, truncate, wordwrap, strpad, str_replace, strip_tags, leftpad, rightpad, rtl, shuffle, time_diff, localizeddate, localizednumber, localizedcurrency, mailto, var_dump, revision, sortbyfield
strftime
根据区域设置格式化本地时间/日期。
Posted at {{ article.date | strftime('%d.%m.%Y %H:%M:%S') }}
示例将输出 发布于 04.01.2016 22:57:42。有关更多格式参数,请参阅此处。
uppercase
将字符串转换为大写。
Hello I'm {{ 'Jack' | uppercase }}
示例将输出 Hello I'm JACK。
lowercase
将字符串转换为小写。
Hello I'm {{ 'JACK' | lowercase }}
示例将输出 Hello I'm jack。
ucfirst
将字符串的第一个字符转换为大写。
Hello I'm {{ 'jack' | ucfirst }}
示例将输出 Hello I'm Jack。
lcfirst
将字符串的第一个字符转换为小写。
Hello I'm {{ 'Jack' | lcfirst }}
示例将输出 Hello I'm jack。
ltrim
从字符串的开始处删除空白(或其他字符)。
Hello I'm {{ ' jack' | ltrim }}
示例将输出 Hello I'm jack,没有开头的空白。
rtrim
从字符串的末尾删除空白(或其他字符)。
Hello I'm {{ 'jack ' | rtrim }}
示例将输出 Hello I'm jack,没有结尾的空白。
str_repeat
重复一个字符串。
I'm the {{ 'best' | str_repeat(3) }}!
示例将输出 I'm the best best best!。
复数
获取英语单词的复数形式。
You have {{ count }} new {{ 'mail' | plural(count) }}
示例将输出 你有 1 封新邮件 或 你有 3 封新邮件 - 根据邮件数量而定。
截断
使用截断过滤器在达到限制后截断字符串。
{{ "Hello World!" | truncate(5) }}
示例将输出 Hello...,其中 ... 是默认分隔符。
您还可以通过将第二个参数设置为 true 来告诉截断保留整个单词。如果最后一个单词在分隔符上,截断将打印出整个单词。
{{ "Hello World!" | truncate(7, true) }}
这里会打印出 Hello World!。
如果您想更改分隔符,只需将第三个参数设置为所需的分隔符。
{{ "Hello World!" | truncate(7, false, "??") }}
此示例将打印 Hello W??。
单词换行
使用单词换行过滤器将文本拆分为等长的行。
{{ "Lorem ipsum dolor sit amet, consectetur adipiscing" | wordwrap(10) }}
此示例将打印
Lorem ipsu
m dolor si
t amet, co
nsectetur
adipiscing
默认分隔符是 "\n",但您可以通过提供分隔符来轻松更改它
{{ "Lorem ipsum dolor sit amet, consectetur adipiscing" | wordwrap(10, "zz\n") }}
这将得到以下结果
Lorem ipsuzz
m dolor sizz
t amet, cozz
nsectetur zz
adipiscing
strpad
使用另一字符串从两侧填充字符串到特定长度。
{{ 'xxx' | strpad(7, 'o') }}
这将打印
ooxxxoo
str_replace
将搜索字符串的所有出现替换为替换字符串。
{{ 'Alice' | str_replace('Alice', 'Bob') }}
这将返回
Bob
strip_tags
从字符串中删除 HTML 和 PHP 标签。在第一个参数中,您可以指定允许的标签。
{{ '<p><b>Text</b></p>' | strip_tags('<p>') }}
这将返回
<p>Text</p>
leftpad
使用另一字符串从左侧填充字符串到特定长度。
{{ 'xxx' | leftpad(5, 'o') }}
这将打印
ooxxx
rightpad
使用另一字符串从右侧填充字符串到特定长度。
{{ 'xxx' | rightpad(5, 'o') }}
这将打印
xxxoo
rtl
反转字符串。
{{ 'Hello world!' | rtl }}
这将打印
!dlrow olleH
shuffle
打乱数组。
{{ songs | shuffle }}
或在 foreach 中
{% for fruit in ['apple', 'banana', 'orange'] | shuffle %}
{{ fruit }}
{% endfor %}
time_diff
使用 time_diff 过滤器渲染日期与现在之间的差异。
{{ post.published_at | time_diff }}
上面的示例将输出类似于 4 秒前或 1 个月后的字符串,具体取决于过滤的日期。
输出是 可翻译的。所有翻译都存储在此插件的 /lang
文件夹中。如果您想要更多的区域设置,只需从 此存储库 中复制它们,将 %count%
替换为 :count
,并发送拉取请求到此存储库。
参数
- date: 计算与现在差异的日期。可以是字符串或 DateTime 实例。
- now: 应该用作现在的日期。可以是字符串或 DateTime 实例。不要设置此参数以使用当前日期。
翻译
要获取可翻译的输出,请将 Symfony\Component\Translation\TranslatorInterface 作为构造函数参数。返回的字符串格式为 diff.ago.XXX 或 diff.in.XXX,其中 XXX 可以是任何有效的单位:秒、分钟、小时、天、月、年。
localizeddate
使用 localizeddate 过滤器将日期格式化为表示日期的本地化字符串。请注意,必须安装 php5-intl 扩展/php7-intl 扩展!
{{ post.published_at | localizeddate('medium', 'none', locale) }}
localizeddate 过滤器接受字符串(它必须是 strtotime 函数支持的格式),DateTime 实例或 Unix 时间戳。
参数
- date_format: 日期格式。选择以下格式之一
- 'none': IntlDateFormatter::NONE
- 'short': IntlDateFormatter::SHORT
- 'medium': IntlDateFormatter::MEDIUM
- 'long': IntlDateFormatter::LONG
- 'full': IntlDateFormatter::FULL
- time_format: 时间格式。与上面相同的格式。
- locale: 用于格式的区域设置。如果给出 NULL,Twig 将使用 Locale::getDefault()
- timezone: 日期时区
- format: 可选的格式化或解析时使用的模式。可能的模式在 ICU 用户指南中有文档说明。
localizednumber
使用 localizednumber 过滤器将数字格式化为表示数字的本地化字符串。请注意,必须安装 php5-intl 扩展!
{{ product.quantity | localizednumber }}
在内部,Twig 使用 PHP NumberFormatter::create() 函数来处理数字。
参数
- 样式:可选的日期格式(默认:'decimal')。选择以下格式之一
- 'decimal':NumberFormatter::DECIMAL
- 'currency':NumberFormatter::CURRENCY
- 'percent':NumberFormatter::PERCENT
- 'scientific':NumberFormatter::SCIENTIFIC
- 'spellout':NumberFormatter::SPELLOUT
- 'ordinal':NumberFormatter::ORDINAL
- 'duration':NumberFormatter::DURATION
- 类型:可选的格式化类型(默认:'default')。选择以下类型之一
- 'default':NumberFormatter::TYPE_DEFAULT
- 'int32':NumberFormatter::TYPE_INT32
- 'int64':NumberFormatter::TYPE_INT64
- 'double':NumberFormatter::TYPE_DOUBLE
- 'currency':NumberFormatter::TYPE_CURRENCY
- locale: 用于格式的区域设置。如果给出 NULL,Twig 将使用 Locale::getDefault()
localizedcurrency
使用localizedcurrency过滤器将货币值格式化为本地化字符串。注意,必须安装php5-intl扩展!
{{ product.price | localizedcurrency('EUR') }}
参数
- currency:表示要使用的货币的3位ISO 4217货币代码。
- locale: 用于格式的区域设置。如果给出 NULL,Twig 将使用 Locale::getDefault()
mailto
渲染电子邮件为普通mailto链接,但具有针对机器人的加密!
{{ 'do-not-reply-to-this@gmail.com' | mailto }}
返回类似以下内容
<span id="e846043876">[javascript protected email address]</span><script type="text/javascript">/*<![CDATA[*/eval("var a=\"9IV1G0on6.ryWZYS28iPcNBwq4aeUJF5CskjuLQAh3XdlEz@7KtmpHbTxM-ODg_+Rvf\";var b=a.split(\"\").sort().join(\"\");var c=\"_TtD3O_TXTl3VdfZ@H3KpVdTH\";var d=\"\";for(var e=0;e<c.length;e++)d+=b.charAt(a.indexOf(c.charAt(e)));document.getElementById(\"e846043876\").innerHTML=\"<a href=\\\"mailto:\"+d+\"\\\">\"+d+\"</a>\"")/*]]>*/</script>
将被渲染到页面上,就像普通一样
<a href="mailto:do-not-reply-to-this@gmail.com">do-not-reply-to-this@gmail.com</a>
PHP会加密您的电子邮件地址,并生成解密JavaScript。大多数机器人无法执行JavaScript,这就是它的工作原理。只要访问者启用了JavaScript,他们就不会注意到您使用了此脚本。如果访问者禁用了JavaScript,他们将会看到"[javascript protected email address]"而不是电子邮件地址。
过滤器参数
{{ 'do-not-reply-to-this@gmail.com' | mailto(true, true, 'Let me know', 'my-class') }}
- 第一个布尔参数 = 返回可点击的电子邮件(带链接)
- 第二个布尔参数 = 启用加密
- 第三个字符串参数 = 链接文本(未加密!)
- 第四个(可选)参数 = CSS类名(将渲染 <a mailto:.. class="my-class">..)
var_dump
输出变量的信息。
<pre>{{ users | var_dump }}</pre>
修订版
强制浏览器重新加载缓存的修改/更新过的资产文件。您可以提供格式参数,以便附加的时间戳相应地转换为PHP date()函数。
<img src="{{ 'assets/images/image_file.jpg' | theme | revision("m.d.y.H.i.s") }}" alt="an image" />
将返回类似以下内容
<img src="https://www.example.com/themes/my-theme/assets/image_file.png?12.03.16.04.52.38" alt="An image" />
sortbyfield
按给定的字段(键)对数组/集合进行排序。
{% set data = [{'name': 'David', 'age': 31}, {'name': 'John', 'age': 28}] %}
{% for item in data | sortbyfield('age') %}
{{ item.name }}
{% endfor %}
输出将为:John David
添加新的过滤器和函数
通常,一个项目需要一些特定的函数。这些可以通过将 twig/functions 或 twig/filters 子目录添加到当前主题中,并在其中包含函数和过滤器来实现。TwigExt将加载所有以下划线 **_** 开头并以 .php 结尾的文件,并使包含的过滤器和函数在Twig中可用。
函数的添加方式如下(例如,将它们放置在活动主题目录中的 twig/functions/_myFucntions.php)
<?php
$functions += [
'myConfig' => function ($api_key, $g) {
$res = Settings::get($api_key, $g);
return "Result is: $res";
}
];
过滤器的添加方式如下(例如,将它们放置在活动主题目录中的 twig/filters/_myFucntions.php)
<?php
$filters += [
'replacestring' => function ($greetings, $search, $replace) {
return str_replace($search, $replace, $string);
}
];
过滤器和函数必须提供返回值。一次可以添加多个新的过滤器和函数到相应的数组中。有关详细信息,请参阅Winter的文档。
贡献
欢迎发送pull请求!请将Pull Request发送到master分支。
许可证
Twig扩展插件是开源软件,许可协议为MIT许可证。