Codeigniter + Smarty集成,页眉/页脚模板

时间:2013-07-29 12:25:45

标签: php codeigniter codeigniter-2 smarty3

我通过本教程在CI安装上实现了smarty:http://www.coolphptools.com/codeigniter-smarty

它工作正常,除了通过包含模板中的文件来加载页眉和页脚。

{include file="header.tpl" title="Example Smarty Page" name="$Name"}
...
{include file="footer.tpl"}

有没有办法从控制器或Smarty库类中加载它们?

更清楚地说明我想要的东西;如果没有模板引擎,我只需通过自定义加载器扩展view方法。

例如

class MY_Loader extends CI_Loader {

    function view( $template, $data = array(), $return = false ) {

        $content = parent::view( 'header', $data, $return );
        $content .= parent::view( $template, $data, $return );
        $content .= parent::view( 'footer', $data, $return );

        if( $content )
            return $content;
    }
}

这一直对我有用,但现在我正在尝试聪明,我不能为我的生活弄清楚如何让它像这样工作。

如果有人能指出我正确的方向。那简直太好了。

PS。抱歉,如果之前已经回答过,我在过去的2个小时里一直在谷歌搜索,我似乎找不到任何东西。我的PHP技能充其量只是中级。

3 个答案:

答案 0 :(得分:3)

我不是专家,但不久前我确实要经历过这个问题。 我做的是这样的:

header.tpl

<html>
    <head>
    </head>
    <body>

content.tpl

{include file="header.tpl"}
{include file="$content"}
{include file="footer.tpl"}

footer.tpl

    </body>
</html>

然后,您可以随时通过content.tpl进行智能呼叫,并通过$content传递实际的正文内容。

就像我说的那样,我不是专家,所以语法可能会关闭,并且可能有一种更“正确”的方式来做到这一点,但我认为这个想法就在那里。

希望有所帮助。

答案 1 :(得分:3)

您应该使用{extends}语法来利用template inheritance

从基本模板文件开始(我们称之为template.php)。此文件将包含您的标题页脚代码,并将指定主要内容的位置(以及您要指定的任何其他模板代码块,例如旁边)。 / p>

(我在这里使用了非常简单的HTML,仅用于示例目的。请不要这样编码。)

<强>的template.php:

<html>
<head>
    <title>{$title|default:'Default Page Title'}</title>
    <meta>
    <meta>
</head>
<body>

    <header>
        <h1>My Website</h1>

        <nav>
            <!-- Navigation -->
        </nav>
    </header>

    <section class="content">

        {block name="content"}{/block}

    </section>

    <footer>
        &copy; 2013 My Website
    </footer>

</body>

然后,您的各个页面将{extend}主模板文件,并为所有块指定必要的内容。请注意,您可以使用可选的块和默认值,因此不需要填充所有块(除非您以这种方式编码)。

<强> content_page.php:

{extends file="template.php"}

{block name="content"}

<h2>Content Page</h2>

<p>Some text.</p>

{/block}

答案 2 :(得分:0)

you can user following way to include smarty tpl view in your controller:
$this->smarty->view('content.tpl')

and header.tpl in content page:
{include file='header.tpl'} 
相关问题