簡體   English   中英

在單個php Smarty文件中顯示多個模板

[英]displaying multiple templates in a single php Smarty file

您好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文件。

您不是只想使用include:

像下面這樣:

您的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。

您可以使用網址參數,即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隱藏網址中的參數,因此,mydomain.com/index.php?pag=contact可以輕松變為mydomain.com/contact

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM