文本中的电子邮件地址到 mailto 超链接(可能在 Twig 中?) [英] Email adress in text to mailto hyperlink (possible in Twig?)
问题描述
我有一个名为 contactInfo
的具有文本类型属性的实体.在表单中输入这些详细信息时,用户只能提交没有 html 的文本.通常在此文本区域中的某处输入电子邮件地址(以及更多详细信息).
I have an entity with a text-type attribute called contactInfo
. Users can only submit text without html when entering these details in a form. Often an email address is entered somewhere in this textarea (together with more details).
现在,当我显示此 contactInfo
时,我想将任何电子邮件地址调整为带有 mailto 超链接的电子邮件地址.例如
Now when I display this contactInfo
I would like adjust any email address to an email address with a mailto hyperlink. For example
Email us at: example@email.com.
应该变成:
Email us at: <a href="mailto:example@email.com">example@email.com</a>.
这个怎么办?我可以直接在 Twig 中使用 RegEx 或 Replace 过滤器执行此操作吗?还是我真的应该在控制器中执行此操作?
How to go about this? Can I do this directly in Twig with some RegEx or Replace filter? Or should I really do this in the controller?
推荐答案
你可以创建一个 twig 过滤器,比如mailTo"并做一些像
You can create a twig filter, something like "mailTo" and do something like
<?php
namespace App\Twig;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
class AppExtension extends AbstractExtension
{
public function getFilters()
{
return array(
new TwigFilter('mailTo', array($this, 'mailTo'), array('is_safe' => 'html')),
);
}
public function mailTo(string $text)
{
if(preg_match_all('/[\p{L}0-9_.-]+@[0-9\p{L}.-]+\.[a-z.]{2,6}\b/u',$text,$mails)){
foreach($mails[0]as $mail ){
$text = str_replace($mail,'<a href="mailto:'.$mail.'">'.$mail.'</a>',$text);
}
}
return $text;
}
}
然后在你的模板中像这样使用它
And then use it like this in your template
contactInfo|mailTo
无论如何,不要在数据库中存储mailto:"或html标签,因为它们总是相同的......
Either way, don't store "mailto:" or html tags in database when those are always gonna be the same...
关于树枝自定义过滤器的文档https://symfony.com/doc/current/templating/twig_extension.html
documentation on twig custom filters https://symfony.com/doc/current/templating/twig_extension.html
这篇关于文本中的电子邮件地址到 mailto 超链接(可能在 Twig 中?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!