首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >智能模板引擎-动态添加扩展块

智能模板引擎-动态添加扩展块
EN

Stack Overflow用户
提问于 2014-12-12 14:31:44
回答 2查看 1.9K关注 0票数 1

为我糟糕的英语道歉

我正在尝试使我的php动态地添加到我的模板中,以调用母版块。下面是我当前展示的模板代码和主页。

代码语言:javascript
复制
<!-- default.tpl -->
<!doctype html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8" />
    <title>Project</title>
</head>
<body>
    <div class="container">
        {block name="content"}{/block}
    </div>
    {block name="javascript"}{/block}
</body>

代码语言:javascript
复制
{extends file="default.tpl"}
{block name="content"}
    Hello World 
{/block}

代码语言:javascript
复制
$this->smarty->extends('default.tpl'); //I don't know if is possible do something like this

$this->smarty->blocks('javascript',array('//cdn.jquery.com')); //I don't know if is possible do something like this too

$this->smarty->display('index');
EN

回答 2

Stack Overflow用户

发布于 2014-12-12 14:46:12

Smarty的工作方式与您所描述的差不多,但是语法有点不同。这就是你需要如何写它:

default.tpl (片段)

代码语言:javascript
复制
<body>
<div class="container">
    {$text}
</div>
{foreach from=$javascript item=script}
    <script src="{$script}"></script>
{/foreach}
</body>

index.tpl

代码语言:javascript
复制
{capture name=content}
    Hello world
{/capture}
{include file='default.tpl' text=$smarty.capture.content}

index.php

代码语言:javascript
复制
$this->smarty->assign('javascript', array('//cdn.jquery.com'));
$this->smarty->display('index.tpl');

这就是聪明的工作方式。有关更多信息,请阅读文档。基本用法在第3-13节中作了解释。

更新:这个解决方案提供了Smarty2的做事方式。另外,这个链接指向Smarty 2的文档。我不知道在Smarty 3中实现的所有新特性。然而,这里介绍的方式也适用于Smarty 3(我从2010年开始使用Smarty 3,但从未感觉到需要Smarty 2中没有的特性)。

票数 1
EN

Stack Overflow用户

发布于 2014-12-12 16:31:54

这两个模板文件看起来都很好。问题在PHP文件中:

代码语言:javascript
复制
$this->smarty->extends('default.tpl'); //I don't know if is possible do something like this

没有名为extends()的方法。在模板中使用模板函数{extend}

代码语言:javascript
复制
$this->smarty->blocks('javascript',array('//cdn.jquery.com')); //I don't know if is possible do something like this too

没有名为block()blocks()的方法。您可以像使用index.tpl那样在子模板( content )中定义块的内容,或者将数据分配给模板变量并在模板中显示。标量变量可以使用语法{$variable}显示,而数组可以使用{foreach}内置函数进行迭代。

代码语言:javascript
复制
$this->smarty->display('index');

这也不起作用,因为模板的名称是'index.tpl',而不仅仅是'index'。Smarty并不会自己附加终止。它只是尝试使用您提供的名称来查找文件。

我通过添加

代码语言:javascript
复制
error_reporting(E_ALL);
ini_set('display_errors', '1');

在你的剧本上。不要阻止在开发计算机上显示错误。在生产服务器上只在上执行此操作。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27445836

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档