如何在 symfony2 中从数据库中渲染 Twig 模板

本文介绍了如何在 symfony2 中从数据库中渲染 Twig 模板的处理方法,对大家解决问题具有一定的参考价值

问题描述

我正在开发用 symfony2 编写的应用程序,我想在一些操作/事件之后发送电子邮件......问题是,用户可以定义像电子邮件模板"这样的东西,它们像简单的字符串一样存储在 db 中,例如:这是来自 {{ user }} 的一些电子邮件",我需要为应该使用该模板的电子邮件呈现正文...

I'm working on application written in symfony2 and I want to send email after some action/event... the problem is, that the users can define something like "email templates" which are stores in db like simple string, for example: "This is some email from {{ user }}" and I need to render body for that email which should use that template...

在这个链接的 symfony 文档中:https://symfony.com/doc/2.0/cookbook/email/email.html#sending-emails 渲染视图的方法是 $this->renderView 并且它需要文件路径,例如bundle:controller:file.html.twig",但我的模板是来自数据库的简单字符串...

In symfony documentation from this link: https://symfony.com/doc/2.0/cookbook/email/email.html#sending-emails the method for render view is $this->renderView and it expects the path to file such as "bundle:controller:file.html.twig", but my template is simple string from database...

如何渲染它?

推荐答案

这是一个适用于 Symfony 4(也可能是旧版本,虽然我没有测试过)的解决方案,并允许您使用存储在数据库的方式与在文件系统中使用模板的方式相同.

Here's a solution that works with Symfony 4 (and possibly older versions as well, although I haven't tested it) and allows you to work with templates stored in the database the same way you would work with templates in the filesystem.

此答案假定您使用的是 Doctrine,但如果您使用的是其他数据库库,则相对容易适应.

This answer assumes you're using Doctrine, but is relatively easy to adapt if you're using another database library.

这是一个使用注解的示例类,但您可以使用您已经在使用的任何配置方法.

This is an example class that uses annotations, but you can use whatever configuration method you're already using.

src/Entity/Template.php

<?php
namespace AppEntity;

use DoctrineORMMapping as ORM;

/**
 * @ORMTable(name="templates")
 * @ORMEntity
 */
class Template
{
    /**
     * @var int
     *
     * @ORMColumn(name="id", type="integer")
     * @ORMId
     * @ORMGeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var string
     *
     * @ORMColumn(type="string", nullable=false)
     */
    private $filename;

    /**
     * @var string
     *
     * @ORMColumn(type="text", nullable=false)
     */
    private $source;

    /**
     * @var DateTime
     *
     * @ORMColumn(type="datetime", nullable=false)
     */
    private $last_updated;
}

最少的字段是 filenamesource,但最好包含 last_updated 否则您将失去缓存.

The bare minimum fields are filename and source, but it's a very good idea to include last_updated or you'll lose the benefits of caching.

src/Twig/Loader/DatabaseLoader.php

<?php
namespace AppTwigLoader;

use AppEntityTemplate;
use DoctrineORMEntityManagerInterface;
use Twig_Error_Loader;
use Twig_LoaderInterface;
use Twig_Source;

class DatabaseLoader implements Twig_LoaderInterface
{
    protected $repo;

    public function __construct(EntityManagerInterface $em)
    {
        $this->repo = $em->getRepository(Template::class);
    }

    public function getSourceContext($name)
    {
        if (false === $template = $this->getTemplate($name)) {
            throw new Twig_Error_Loader(sprintf('Template "%s" does not exist.', $name));
        }

        return new Twig_Source($template->getSource(), $name);
    }

    public function exists($name)
    {
        return (bool)$this->getTemplate($name);
    }

    public function getCacheKey($name)
    {
        return $name;
    }

    public function isFresh($name, $time)
    {
        if (false === $template = $this->getTemplate($name)) {
            return false;
        }

        return $template->getLastUpdated()->getTimestamp() <= $time;
    }

    /**
     * @param $name
     * @return Template|null
     */
    protected function getTemplate($name)
    {
        return $this->repo->findOneBy(['filename' => $name]);  
    }
}

类比较简单.getTemplate 从数据库中查找模板文件名,其余方法使用 getTemplate 来实现 Twig 需要的接口.

The class is relatively simple. getTemplate looks up the template filename from the database, and the rest of the methods use getTemplate to implement the interface that Twig needs.

config/services.yaml

services:
    AppTwigLoaderDatabaseLoader:
        tags:
        - { name: twig.loader }

现在您可以像使用文件系统模板一样使用数据库模板.

Now you can use your database templates in the same way as filesystem templates.

从控制器渲染:

return $this->render('home.html.twig');

从另一个 Twig 模板中包含(可以在数据库或文件系统中):

Including from another Twig template (which can be in the database or filesystem):

{{ include('welcome.html.twig') }}

呈现为字符串(其中 $twigTwigEnvironment 的一个实例)

Rendering to a string (where $twig is an instance of TwigEnvironment)

$html = $twig->render('email.html.twig')

在每种情况下,Twig 都会首先检查数据库.如果 DatabaseLoader 中的 getTemplate 返回 null,Twig 将检查文件系统.如果模板在数据库文件系统中不可用,Twig 将抛出 Twig_Error_Loader.

In each of these cases, Twig will check the database first. If getTemplate in your DatabaseLoader returns null, Twig will then check the filesystem. If the template isn't available in the database or the filesystem, Twig will throw a Twig_Error_Loader.

这篇关于如何在 symfony2 中从数据库中渲染 Twig 模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,WP2

admin_action_{$_REQUEST[‘action’]}

do_action( "admin_action_{$_REQUEST[‘action’]}" )动作钩子::在发送“Action”请求变量时激发。Action Hook: Fires when an ‘action’ request variable is sent.目录锚点:#说明#源码说明(Description)钩子名称的动态部分$_REQUEST['action']引用从GET或POST请求派生的操作。源码(Source)更新版本源码位置使用被使用2.6.0 wp-admin/admin.php:...

日期:2020-09-02 17:44:16 浏览:1127

admin_footer-{$GLOBALS[‘hook_suffix’]}

do_action( "admin_footer-{$GLOBALS[‘hook_suffix’]}", string $hook_suffix )操作挂钩:在默认页脚脚本之后打印脚本或数据。Action Hook: Print scripts or data after the default footer scripts.目录锚点:#说明#参数#源码说明(Description)钩子名的动态部分,$GLOBALS['hook_suffix']引用当前页的全局钩子后缀。参数(Parameters)参数类...

日期:2020-09-02 17:44:20 浏览:1032

customize_save_{$this->id_data[‘base’]}

do_action( "customize_save_{$this-&gt;id_data[‘base’]}", WP_Customize_Setting $this )动作钩子::在调用WP_Customize_Setting::save()方法时激发。Action Hook: Fires when the WP_Customize_Setting::save() method is called.目录锚点:#说明#参数#源码说明(Description)钩子名称的动态部分,$this->id_data...

日期:2020-08-15 15:47:24 浏览:775

customize_value_{$this->id_data[‘base’]}

apply_filters( "customize_value_{$this-&gt;id_data[‘base’]}", mixed $default )过滤器::过滤未作为主题模式或选项处理的自定义设置值。Filter Hook: Filter a Customize setting value not handled as a theme_mod or option.目录锚点:#说明#参数#源码说明(Description)钩子名称的动态部分,$this->id_date['base'],指的是设置...

日期:2020-08-15 15:47:24 浏览:866

get_comment_author_url

过滤钩子:过滤评论作者的URL。Filter Hook: Filters the comment author’s URL.目录锚点:#源码源码(Source)更新版本源码位置使用被使用 wp-includes/comment-template.php:32610...

日期:2020-08-10 23:06:14 浏览:903

network_admin_edit_{$_GET[‘action’]}

do_action( "network_admin_edit_{$_GET[‘action’]}" )操作挂钩:启动请求的处理程序操作。Action Hook: Fires the requested handler action.目录锚点:#说明#源码说明(Description)钩子名称的动态部分$u GET['action']引用请求的操作的名称。源码(Source)更新版本源码位置使用被使用3.1.0 wp-admin/network/edit.php:3600...

日期:2020-08-02 09:56:09 浏览:848

network_sites_updated_message_{$_GET[‘updated’]}

apply_filters( "network_sites_updated_message_{$_GET[‘updated’]}", string $msg )筛选器挂钩:在网络管理中筛选特定的非默认站点更新消息。Filter Hook: Filters a specific, non-default site-updated message in the Network admin.目录锚点:#说明#参数#源码说明(Description)钩子名称的动态部分$_GET['updated']引用了非默认的...

日期:2020-08-02 09:56:03 浏览:834

pre_wp_is_site_initialized

过滤器::过滤在访问数据库之前是否初始化站点的检查。Filter Hook: Filters the check for whether a site is initialized before the database is accessed.目录锚点:#源码源码(Source)更新版本源码位置使用被使用 wp-includes/ms-site.php:93910...

日期:2020-07-29 10:15:38 浏览:809

WordPress 的SEO 教学:如何在网站中加入关键字(Meta Keywords)与Meta 描述(Meta Description)?

你想在WordPress 中添加关键字和meta 描述吗?关键字和meta 描述使你能够提高网站的SEO。在本文中,我们将向你展示如何在WordPress 中正确添加关键字和meta 描述。为什么要在WordPress 中添加关键字和Meta 描述?关键字和说明让搜寻引擎更了解您的帖子和页面的内容。关键词是人们寻找您发布的内容时,可能会搜索的重要词语或片语。而Meta Description则是对你的页面和文章的简要描述。如果你想要了解更多关于中继标签的资讯,可以参考Google的说明。Meta 关键字和描...

日期:2020-10-03 21:18:25 浏览:1620

谷歌的SEO是什么

SEO (Search Engine Optimization)中文是搜寻引擎最佳化,意思近于「关键字自然排序」、「网站排名优化」。简言之,SEO是以搜索引擎(如Google、Bing)为曝光媒体的行销手法。例如搜寻「wordpress教学」,会看到本站的「WordPress教学:12个课程…」排行Google第一:关键字:wordpress教学、wordpress课程…若搜寻「网站架设」,则会看到另一个网页排名第1:关键字:网站架设、架站…以上两个网页,每月从搜寻引擎导入自然流量,达2万4千:每月「有机搜...

日期:2020-10-30 17:23:57 浏览:1264