我在客戶端和服務器之間共享模板,並希望在腳本標記內輸出原始模板,這是可能的,逐字。可以逐字使用包含的內容嗎?
http://twig.sensiolabs.org/doc/tags/verbatim.html
但是它會更好,如果這可以作爲過濾器的,但它似乎包括不能夠被應用?
我是新來的樹枝,所以如果我錯過了明顯的功能,請原諒我。
我在客戶端和服務器之間共享模板,並希望在腳本標記內輸出原始模板,這是可能的,逐字。可以逐字使用包含的內容嗎?
http://twig.sensiolabs.org/doc/tags/verbatim.html
但是它會更好,如果這可以作爲過濾器的,但它似乎包括不能夠被應用?
我是新來的樹枝,所以如果我錯過了明顯的功能,請原諒我。
我遇到了同樣的問題,這個頁面出現在我的搜索結果中。在問題得到解答之後,Twig開發人員將此功能添加到庫中。我想我應該爲未來的搜索者添加一些細節。
使用source
函數可以完成包括原始文本(也稱爲使用與Twig相同語法的客戶端模板)的功能。
即:{{ source('path/to/template.html.twig') }}
我也在尋找類似的東西,因爲我使用Twig.js進行一些客戶端模板以及Symfony。我試圖在服務器端和客戶端代碼之間共享模板,因此我需要在某些情況下解析內容,並在其他情況下逐字處理,事實證明這有點棘手。
我找不到任何內置在Twig中的東西來幫助解決這個問題,但幸運的是,擴展Twig以獲得所需內容非常簡單。我將它作爲一個函數來實現,但您也可以將它作爲一個過濾器來執行。
services.yml
statsidekick.twig.include_as_template_extension:
class: StatSidekick\AnalysisBundle\Twig\IncludeAsTemplateExtension
tags:
- { name: twig.extension }
IncludeAsTemplateExtension.php在枝杈
<?php
namespace StatSidekick\AnalysisBundle\Twig;
use Twig_Environment;
use Twig_Extension;
class IncludeAsTemplateExtension extends Twig_Extension {
/**
* Returns a list of global functions to add to the existing list.
*
* @return array An array of global functions
*/
public function getFunctions() {
return array(
new \Twig_SimpleFunction('include_as_template', array($this, 'includeAsTemplate'), array('needs_environment' => true, 'is_safe' => array('html')))
);
}
function includeAsTemplate(Twig_Environment $env, $location, $id) {
$contents = $env->getLoader()->getSource($location);
return "<script data-template-id=\"{$id}\" type=\"text/x-twig-template\">{$contents}</script>";
}
/**
* Returns the name of the extension.
*
* @return string The extension name
*/
public function getName() {
return 'include_as_template_extension';
}
}
使用文件
{{ include_as_template('Your:Template:here.html.twig', 'template-id') }}
如果你有一個枝杈文件是這樣的:
<ul class="message-list">
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
輸出將是這樣的:
<script data-template-id="template-id" type="text/x-twig-template">
<ul class="message-list">
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
</script>
的工作是從卡里Söderholm的回答here的。希望有所幫助!
請explan爲什麼它會是一個更好的過濾器。我看不到原因 – seferov 2013-02-22 14:57:38
您是否嘗試過[raw](http://twig.sensiolabs.org/doc/filters/raw.html)? – cheesemacfly 2013-02-22 15:43:37