inside .tpl:
{assign var="datasheet" value=$product->reference|escape:'htmlall':'UTF-8'}
... ...
{testsk}
function.testsk.php:
<?php
function smarty_function_testsk(){
$ch = curl_init ("http://www.domain.com/path/to/".$smarty->get_template_vars('datasheet')."/name.html");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$page = curl_exec($ch);
preg_match("/'s<div id='"divname'">(.*)<'/div>/siU", $page, $matches);
foreach ($matches as &$match) {
$match = $match;
}
echo '<table>';
echo $matches[1];
echo '</table>';
}
?>
显然它不起作用,但对于给定的已知变量函数是好的和经过测试的我也试图允许PHP标签进入smarty类,它允许,但我不能访问smarty变量。
工作原理:
{php}
$ch = curl_init ("http://www.domain.com/path/to/3345674/name.html");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$page = curl_exec($ch);
preg_match("/'s<div id='"divname'">(.*)<'/div>/siU", $page, $matches);
foreach ($matches as &$match) {
$match = $match;
}
echo '<table>';
echo $matches[1];
echo '</table>';
{/php}
IT DOESN'T WORK:
{assign var="datasheet" value=$product->reference|escape:'htmlall':'UTF-8'}
{php}
$v1 = $this->get_template_vars('datasheet');
$ch = curl_init ("http://www.domain.com/path/to/".$v1."/name.html");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$page = curl_exec($ch);
preg_match("/'s<div id='"divname'">(.*)<'/div>/siU", $page, $matches);
foreach ($matches as &$match) {
$match = $match;
}
echo '<table>';
echo $matches[1];
echo '</table>';
{/php}
错误:Fatal error: Using $this when not in object context in /var/www/vhosts/domain.com/httpdocs/folder/tools/smarty/plugins/block.php.php(23) : eval()'d code on line 2
我不知道为什么$smarty->get_template_vars('datasheet')在这里失败,但您可以通过显式传递参数并使用$inParam[]:
读取来解决它。tpl文件
{assign var="datasheet" value=$product->reference|escape:'htmlall':'UTF-8'}
... ...
{testsk datasheet=$datasheet}
function.testsk.php
<?php
function smarty_function_testsk($inParam, $inSmarty){
$ch = curl_init ("http://www.domain.com/path/to/".$inParam['datasheet']."/name.html");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$page = curl_exec($ch);
preg_match("/'s<div id='"divname'">(.*)<'/div>/siU", $page, $matches);
foreach ($matches as &$match) {
$match = $match;
}
echo '<table>';
echo $matches[1];
echo '</table>';
}
?>
[代码未测试]
http://www.smarty.net/docs/en/plugins.functions.tpl(以上编辑以分离文件内容。下面是new)
我假设是smarty v3。对于版本2.x应该类似地工作。
在{php}中的smarty .tpl文件中…{/php}你在全局作用域,使用$smarty->get_template_vars('var_name');而不是$this->get_template_vars('var_name');
再看一下你的原始代码,$smarty->get_template_vars()失败,因为$smarty没有在函数作用域中定义,所以你得到null(和一个关于未定义变量的通知)。将"global $smarty;"作为插件函数体的第一行,或者最好更改函数的参数声明"function smarty_function_testsk($param, $smarty)",它将$smarty定义为当前模板对象的实例。