聪明的模板

时间:2012-08-29 20:27:10

标签: php smarty

所以这就是问题,我有一个index.php(包含所有的PHP代码),我有一个index.tpl文件,其中包含所有的html内容。但现在因为我使用ajax我有另一个php文件应该输出一些数据(data.php)。问题是我不知道如何在data.php文件中选择模板,我所知道的是index.php我有一个显示tpl ($Smarty->display($filename);的函数但我不知道想要在data.php文件中再次显示模板我只想分配一些需要在index.tpl上显示的变量

编辑:

好的,这会很长: 首先,我需要解释一下我想要完成的任务。我有index.php和data.php。 index.php:

<?php
include("../include/config.php");
include("../include/functions/import.php");

$thebaseurl = $config['baseurl'];

    $query ="SELECT name FROM contacts";
    $results = $conn->execute($query);
    $select-names = $results->getrows();
    STemplate::assign('select-names',$select-names);

$templateselect = "index.tpl";
STemplate::display($templateselect);
?>

index.tpl有点长,所以我将发布重要部分:

xmlhttp.open("get","data.php?q="+str,true);

这是AJAX代码,此代码将GET方法中的+ str值发送到data.php文件,然后使用该值并从数据库中提取一些数据。

data.php:

$q=$_GET["q"];

$sql="SELECT * FROM contacts WHERE name = '$q'";

$result = mysql_query($sql);


while($row = mysql_fetch_array($result))
  {
    $name = $row['name'];
  }

STemplate::assign('name',$name);
$templateselect = "index.tpl";
STemplate::display($templateselect); //the second display
?>

我在这里使用STemplate这个类来获得聪明的功能,但是你得到了什么是代码。

我希望你明白现在的问题是什么。如何在不再显示模板文件的情况下将变量分配给模板。这样,$ name变量可以在index.tpl中访问(名称从数据库中显示),但由于data.php中的显示功能,整个内容再次显示。

2 个答案:

答案 0 :(得分:1)

使用$smarty->assign('var', 'value');分配值。

有关详细信息,请阅读更多here

修改

.tpl背后的想法是使用assign输入变量,当页面准备就绪时,使用display显示它。您可以在显示之前设置多个变量:

<?php

$smarty = new Smarty();

$smarty->assign('firstname', 'Doug');
$smarty->assign('lastname', 'Evans');
$smarty->assign('meetingPlace', 'New York');

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

?>

如果你看到两次文字,那就意味着某个地方你曾经过多次调用$smarty->display('index.tpl');。要准确找到我必须查看您的来源的位置。请发布文件或有问题的位。

无论如何,祝你好运:)。

答案 1 :(得分:1)

不知道这是否有帮助。但是你也可以将'render'tpl返回给你的AJAX。显示功能通常用于页面的框架。 (有点像所有东西的基本占位符)。并用于页面刷新,而不是AJAX。

在data.php中,您可以使用

$answer = $smarty->fetch("ajaxreturn.tpl");
echo $answer;
die();
在此之前,你可以在Smarty中做所需的任务。

在AJAX中,您可以将返回的HTML片段放在正确的位置。