如何在 symfony2 中从数据库中渲染 Twig 模板 [英] How to render Twig template from database in symfony2

查看:17
本文介绍了如何在 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 模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆