Domanda

Sto usando Smarty e PHP. Se ho un modello (o come file o come stringa), c'è un modo per ottenere smarty per analizzare quel file / stringa e restituire un array con tutte le variabili di smarty in quel modello?

es .: voglio qualcosa del genere:

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

Il motivo per cui voglio fare questo è perché voglio che gli utenti siano in grado di inserire i modelli stessi e quindi compilarli in un secondo momento. Quindi devo essere in grado di ottenere un elenco delle variabili presenti in questi modelli.

Supponiamo che sto facendo solo variabili semplici (es: no " {$ object.method} " o " {$ varaible | function} "), e che non includo altri template .

È stato utile?

Soluzione 2

Sembra che non ci sia un modo integrato per farlo.

Altri suggerimenti

Se hai bisogno di variabili nascoste in cose come {if $ var% 2} andrei con questo tipo di codice:

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

Se vuoi anche catturare cose del genere: {if $ var! = $ var2} segue una versione migliore

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

Normalmente sono contrario alle espressioni regolari, ma questo mi sembra un caso valido. Puoi usare preg_match_all () per farlo (se vuoi solo variabili come $ {this} ):

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

Mi rendo conto che questo thread è vecchio, ma questa è la soluzione integrata.

Penso che quello che stai cercando sia la console di debug .

Questa console mostra tutte le variabili utilizzate nei modelli coinvolti nella tua pagina web.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top