2015-11-01 86 views
0

你好,stackoverflow社区!在单个php Smarty文件中显示多个模板

我一直无法找到这个问题的答案。我有一个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} 

我包括我的named通过一个称为主文件的内容编制索引块.tpl:

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

问题是: 一切工作,豪ver,在这种情况下,我将不得不创建大量的php文件(如contact.php),这些文件显示正确的模板。我该如何处理单个php文件,并根据用户点击的页面链接来显示正确的模板?例如。当用户点击联系人页面时,我希望它显示contact.tpl,当用户点击'about'页面时,我希望它显示about.tpl,而不必为每种情况分别创建一个php文件。

回答

0

难道你不希望只使用一个包括:

象下面这样:

你的PHP显示 “contact.tpl”:

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

进入contact.tpl为例,你需要来自另一个tpl的索引。

这里是你的contact.tpl:

{include file="index.tpl"} 

{block name="content"} 
    my form.... 
{/block} 

这样你就会显示在同一页面中同时contact.tpl和index.tpl里。

0

您可以使用URL参数即的index.php?PAG =接触,的index.php?PAG =家庭

,然后在你的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'=>'[email protected]'); 
    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