簡體   English   中英

PHP Smarty - 獲取模板中所有變量的列表?

[英]PHP Smarty - Get a list of all the variables in a template?

我正在使用Smarty和PHP。 如果我有一個模板(作為文件或字符串),有沒有辦法讓smarty解析該文件/字符串並返回一個包含該模板中所有smarty變量的數組?

例如:我想要這樣的事情:

$mystring = "Hello {$name}. How are you on this fine {$dayofweek} morning";
$vars = $smarty->magically_parse( $string );
// $vars should now be array( "name", "dayofweek" );

我想這樣做的原因是因為我希望用戶能夠自己輸入模板,然后在以后填寫它們。 因此,我需要能夠獲得此模板中的變量列表。

讓我們假設我只做簡單的變量(例如:no“{$ object.method}”或“{$ varaible | function}”),而且我不包括任何其他模板。

如果您需要隱藏在{if $var%2}類的變量中,我會使用這種代碼:

preg_match_all('`{[^\\$]*\\$([a-zA-Z0-9]+)[^\\}]*}`', $string, $result);
$vars = $result[1];

如果你還想捕捉這樣的東西: {if $var != $var2}接下來是更好的版本

function getSmartyVars($string){
  // regexp
  $fullPattern = '`{[^\\$]*\\$([a-zA-Z0-9]+)[^\\}]*}`';
  $separateVars = '`[^\\$]*\\$([a-zA-Z0-9]+)`';

  $smartyVars = array();
  // We start by extracting all the {} with var embedded
  if(!preg_match_all($fullPattern, $string, $results)){
    return $smartyVars;
  }
  // Then we extract all smarty variables
  foreach($results[0] AS $result){
    if(preg_match_all($separateVars, $result, $matches)){
      $smartyVars = array_merge($smartyVars, $matches[1]);
    }
  }
  return array_unique($smartyVars);
}

看起來沒有一種內置的方式來做到這一點。

通常我反對正則表達式,但這看起來像是一個有效的案例。 您可以使用preg_match_all()來執行此操作(如果您只需要${this}類的變量):

preg_match_all('\{\$(.*?)\}', $string, $matches, PREG_PATTERN_ORDER);
$variableNames = $matches[1];
{debug}

我意識到這個線程已經老了,但這是內置的解決方案。

我認為你要找的是調試控制台

此控制台顯示網頁中涉及的模板中使用的所有變量。

暫無
暫無

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

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