【问题标题】:displaying multiple templates in a single php Smarty file在单个 php Smarty 文件中显示多个模板
【发布时间】:2015-11-01 09:31:09
【问题描述】:

你好 stackoverflow 社区!

我无法找到这个问题的答案。我有一个如下所示的contact.php 文件:

<?php
require_once('lib/smarty/smarty/libs/Smarty.class.php');
$smarty = new Smarty();

$smarty->caching        = false;
$smarty->debugging         = false;
$smarty->template_dir     = $_SERVER['DOCUMENT_ROOT'].'/templates/';
$smarty->compile_dir      = $_SERVER['DOCUMENT_ROOT'].'/cache/smarty/templates_c';
$smarty->cache_dir        = $_SERVER['DOCUMENT_ROOT'].'/cache/smarty/cache';

$smarty->display('contact.tpl');

die;

在我的contact.tpl 文件中,我有我的表单:

    {extends file="index.tpl"} 
    {block name="content"}
    my form....
    {/block}

我通过一个名为 index.tpl 的主文件包含我的名为 content 的块:

<!DOCTYPE html>
<main>
...
     {block name="content"}{/block}
</main>

问题: 一切正常,但是,在这种情况下,我必须创建大量显示正确模板的 php 文件(如 contact.php)。如何处理单个 php 文件,并根据用户单击的页面链接让它显示正确的模板?例如。当用户单击联系页面时,我希望它显示contact.tpl,当用户单击“关于”页面时,我希望它显示about.tpl,而无需为每种情况提供单独的php 文件。

【问题讨论】:

    标签: php smarty


    【解决方案1】:

    您不是只想使用包含:

    如下:

    您的 PHP 显示“contact.tpl”:

    $smarty->display('contact.tpl');
    

    以contact.tpl为例,您需要另一个tpl的索引。

    这是您的联系方式。tpl:

    {include file="index.tpl"}
    
    {block name="content"}
       my form....
    {/block}
    

    这样您将在同一页面中同时显示contact.tpl 和index.tpl。

    【讨论】:

      【解决方案2】:

      您可以使用 url 参数,即 index.php?pag=contact、index.php?pag=home

      然后在您的 index.php 中,只需使用开关即可

      switch ($_GET['pag'])
      {
         case 'contact':
            $template="contact.tpl";
            //you can also declare some variables for one particular view to use them in the template
            $data=array('my_mail'=>'test@test.com');
         break;
      
         case 'home':
            $template="home.tpl";
         break;
      
         default:
            $template="error404.tpl";
         break;
      
      }
      
      $smarty->assign(array('data'=>$data,'something_else'=>$more_data));
      $smarty->display($template);
      

      你可以使用htaccess隐藏url中的参数,所以mydomain.com/index.php?pag=contact可以很容易地变成mydomain.com/contact

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-16
        相关资源
        最近更新 更多