displaying multiple templates in a single php Smarty file

爱⌒轻易说出口 提交于 2020-01-07 03:05:07

问题


Hello stackoverflow community!

I haven't been able to find an answer to this problem. I have a contact.php file which looks like this:

<?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;

in my contact.tpl file I have my form:

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

And I include my block named content through a master file called index.tpl:

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

THE PROBLEM: Everything is working, however, in this case I would have to create a large number of php files (like contact.php) which are displaying the right template. How can I go about with a single php file, and get it to display the right template depending on what page link the user clicks on? E.g. when the user clicks on the contact page, I would like it to display contact.tpl, when the user clicks on the 'about' page, I would like it to display about.tpl without having a separate php file for each case.


回答1:


Aren't you looking to just use an include :

Like below :

Your PHP display "contact.tpl":

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

and into contact.tpl as example you need the index from another tpl.

Here is your contact.tpl :

{include file="index.tpl"}

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

This way you'll display both contact.tpl and index.tpl within the same page.




回答2:


You can use url parameters i.e. index.php?pag=contact, index.php?pag=home

and then in your index.php it's just a matter of using a switch

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);

You can hide the parameters in the url using htaccess, so, mydomain.com/index.php?pag=contact can easily become mydomain.com/contact



来源:https://stackoverflow.com/questions/33460807/displaying-multiple-templates-in-a-single-php-smarty-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!