dongwo5449 2014-12-12 14:31
浏览 68

Smarty模板引擎 - 动态添加块

[Sorry for my bad english]

I'm trying to make my php dynamically add to my template to call the masterpage block. Below is my current show how the template code and masterpage.

------------------- default.tpl -------------------------

<!-- 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>

------------------- index.tpl -------------------------

{extends file="default.tpl"}
{block name="content"}
    Hello World 
{/block}

------------------- index.php -------------------------

$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');
  • 写回答

2条回答 默认 最新

  • duanlan3598 2014-12-12 14:46
    关注

    Smarty works almost the way you described but the syntax is a little bit different. This is how you need to write it:

    default.tpl (fragment)

    <body>
    <div class="container">
        {$text}
    </div>
    {foreach from=$javascript item=script}
        <script src="{$script}"></script>
    {/foreach}
    </body>
    

    index.tpl

    {capture name=content}
        Hello world
    {/capture}
    {include file='default.tpl' text=$smarty.capture.content}
    

    index.php

    $this->smarty->assign('javascript', array('//cdn.jquery.com'));
    $this->smarty->display('index.tpl');
    

    This is how Smarty works. For more information, please read the documentation. The basic usage is explained in sections 3-13.

    Update: this solution presents the Smarty 2 way of doing things. Also, the link goes to the documentation for Smarty 2. I wasn't aware of all the new features implemented in Smarty 3. However, the way presented here works in Smarty 3 as well (I'm using Smarty 3 since 2010 but never felt the need for features that were not present in Smarty 2.)

    评论

报告相同问题?

悬赏问题

  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决