扩展Twig以定义资产url


extend Twig to define assets url

我阅读了用于管理模板中资产的Silex Cookbookhttp://silex.sensiolabs.org/doc/cookbook/assets.html

并在我的app/app.php:中编写此代码

$app['twig'] = $app->share($app->extend('twig', function ($twig, $app) {
    $twig->addFunction(new 'Twig_SimpleFunction('asset', function ($asset) {
        // implement whatever logic you need to determine the asset path
        return sprintf('http://assets.examples.com/%s', ltrim($asset, '/'));
    }));
    return $twig;
}));
$app->get('/', function () use ($app) {
    return $app['twig']->render('index.twig', array(
        'title' => "Hello World",
        'colors' => array("red", "green", "yellow"),
    ));
});

index.twig包含:

{% extends "layout.twig" %}
{% block title %}
    {{ title }}
{% endblock %}
{% block content %}
    <h1>{{ title }}</h1>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi quibusdam numquam laudantium eum asperiores non libero odio quae debitis beatae perferendis eius esse molestiae voluptatum vel inventore quasi. Quo sint sequi sunt amet sapiente tempora autem iusto praesentium rerum ducimus.</p>
    <ul>
        {% for color in colors %}
            <li>{{ color }}</li>        
        {% endfor %}
    </ul>
    {{ asset('/css/styles.css') }}
{% endblock %}

一切都很好,但当我在另一个twig文件中使用asset时,我会收到以下错误:

Twig_Error_Syntax in Parser.php line 370:
A template that extends another one cannot have a body in "admin/dashboard.twig" at line 3.

例如,我的AdminDashboard控制器包含:

<?php

namespace App'Controller'Admin;
use Silex'Application;
class AdminDashboard
{
    function __construct()
    {
        return "Dashboard";
    }
    function indexAction(Application $app)
    {
        return $app['twig']->render('admin/dashboard.twig', array(
            'title' => "Hello World",
            'colors' => array("red", "green", "yellow"),
        ));
    }

}

admin/dashboard.twig包含:

{% extends "layout.twig" %}
{{ asset('/css/styles.css') }}

但当我访问我的admin页面时,我得到了上面的错误。

只需阅读错误消息,它与函数调用无关:

扩展另一个模板的模板不能具有主体

admin/dashboard.twig文件的第一行有{% extends ... %},这意味着它扩展了另一个模板。正如您在错误消息中看到的,扩展另一个模板的模板不能有正文。它只能填充父模板定义的块。