扩展Twig定义资产网址

玛姬菲

我阅读了Silex Cookbook有关模板中的资产管理的http://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 %}

一切正常,但是当我asset在另一个twig文件中使用时会出现此错误:

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 ... %}在第一行,这意味着它扩展了另一个模板。正如您在错误消息中看到的那样,扩展另一个模板的模板不能具有主体。它只能填充父模板定义的块。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章