首先,你可能需要創建和使用數據庫模板加載器,這裏有一個例子(它的有點難看,但它的工作原理) :
class DBTwigLoader implements \Twig_LoaderInterface, \Twig_ExistsLoaderInterface
{
protected $dbh;
protected $table;
public function __construct(\PDO $dbh, $table = 'tmpl_twig')
{
$this->dbh = $dbh;
$this->table = $table;
}
public function getSource($name)
{
if (false === $source = $this->getValue('source', $name)) {
throw new \Twig_Error_Loader(sprintf('Template "%s" does not exist.', $name));
}
return $source;
}
// Twig_ExistsLoaderInterface as of Twig 1.11
public function exists($name)
{
return $name === $this->getValue('name', $name);
}
public function getCacheKey($name)
{
return $name;
}
public function isFresh($name, $time)
{
if (false === $lastModified = $this->getValue('last_modified', $name)) {
return false;
}
return $lastModified <= $time;
}
protected function getValue($column, $name)
{
$sth = $this->dbh->prepare('SELECT ' . $column . ' FROM '.$this->table.' WHERE name = :name');
$sth->execute(array(':name' => (string)$name));
return $sth->fetchColumn();
}
}
之後,你可以渲染做到這一點:
$loader = new DBTwigLoader($dbh);
$twig = new Twig_Environment($loader);
//echo $twig->render('index.twig', array('name' => 'Fabien'));
//or eventually Im doing that (I use just some blocks):
$template = $twig->loadTemplate($messagesPayload['template_name']);
$bodyHtml = $template->renderBlock('bodyHtml', ['recipient' => $recipient]);
Template_name將是'yourtempname',它將在db的名稱列下。請確保您準備架構,爲一點的更多細節看看是:使用包裝樹枝,只是一個服務
{% block subject 'Welcome to newsletter, ' ~ data.name %}
{% block bodyHtml %}
<div style="background-color: black; color: lime;">
Here is <strong>free trial of our new soft</strong>.
As of our experience <strong><i>we think that:</i></strong><br/> {{ data.message }}
</div>
{% endblock %}
眼下林:http://twig.sensiolabs.org/doc/recipes.html#using-a-database-to-store-templates與上面的代碼工作
樣品模板此服務從數據庫呈現模板,但我認爲如果您發現它更方便,您可以將它連接到您的基本Twig服務。
從字符串
模板我不知道爲什麼你在模板中使用常量,但它會更好,將它們轉換成適當的枝條模板即[OWNER_NAME]以{{OWNER_NAME }}然後如果你不想要的模板轉換數據庫,那麼你可以使用str_replace()函數的功能,以取代枝杈將替換值的關懷......
class DefaultController extends Controller
{
public function indexAction()
{
//this will create twig template from string and array of data
$template = $this->get('twig')->createTemplate(
"testing {{OWNER_NAME}} tests {{CUSTOMER}}"
);
$templateString = $template->render(
array('OWNER_NAME'=>'Joe', 'CUSTOMER' => 'some customer')
);
// if you're not using it yet, try out dump (VarDumper component),
//included in Symfony standard, it will show in webtoolbar as well
dump($template);
dump($templateString);
//return response if in controller (*using symfony 3.2)
return new Response($templateString);
}
}
[[{{在和]與} }在傳遞給crateTemplate函數之前。
如果你決定堅持使用[[VAR]]格式,那麼str_replace()或更好的preg_replace_(全部)可以爲你找到答案,但如果你使用Symfony和樹枝,我不明白這一點。
Actualy,我沒有在數據庫中存儲完整的模板我只將內容部分存儲在db列中。有沒有其他方法可以在發送電子郵件的同時在運行時找到替換這些變量的值。 –
看看我的編輯 –