<?php
echo Templation::Run("hello {{world}} how are {{world}}", $data = array('world'=>'WORLD!', 'you'=>'YOU!'));
class Templation
{
/**
* Mark the templated variable with a special class in html so javascript can use it also.
* @param $match
* @param $replace_with
* @return string
*/
private static function enclose($match, $replace_with){
return '<span class="Templation" title='.json_encode(htmlentities($match)).' data-Templation='.json_encode(htmlentities($match)).'>'.$replace_with.'</span>';
}
/**
* Run the template through with the given data and return a result
* optionally enclosing each replacement with a <span class="Templation">
* For the JavaScript version to run correctly.
* @see Templation.js
*
* @param $template
* @param $data
* @return string
*/
public static function Run($template, $data, $enclose = true){
$result = $template;
preg_match_all('/{{([^}]+?)}}/im', $template, $matches, PREG_PATTERN_ORDER);
$matches = $matches[0];
foreach($matches as $i => $match){
if (strpos($match, '||') !== false){
$replace_with = self::PriorityReplace($match, $data);
$result = str_replace($match, $enclose ? self::enclose($match, $replace_with) : $replace_with, $result);
}else{
$match2 = preg_replace("/(\\{\\{|\\}\\})/", "", $match);
if (isset($data[$match2])){
$result = str_replace($match, $enclose ? self::enclose($match, $data[$match2]) : $data[$match2], $result);
}else{
$result = str_replace($match, $enclose ? self::enclose($match, $match) : $match, $result);
}
}
}
return $result;
}
/**
* Do a Priority Replacement based on the fact that there is || as a delimiter
* This means that currently literal text with a '||' is not supported
* for example {{var5||var4||var3||'Hello || World'}} will break it. (too many features would slow it down)
*
* @param $match
* @param $data
* @return mixed|string
*/
public static function PriorityReplace($match, $data){
$match = preg_replace("/(\\{\\{|\\}\\})/", "", $match);
$p = explode('||', $match);
//var_dump($p);
for($i = 0; $i < count($p); ++$i){
if (strpos($p[$i], '\'') !== false){
return trim($p[$i],"'");
}
else if (isset($data[$p[$i]])){
return $data[$p[$i]];
}
}
return $match;
}
}
Warning: PHP Startup: Unable to load dynamic library 'sodium.so' (tried: /usr/lib/php/8.3.5/modules/sodium.so (libsodium.so.23: cannot open shared object file: No such file or directory), /usr/lib/php/8.3.5/modules/sodium.so.so (/usr/lib/php/8.3.5/modules/sodium.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0
hello <span class="Templation" title="<span class="Templation" title="{{world}}" data-Templation="{{world}}">WORLD!</span>" data-Templation="<span class="Templation" title="{{world}}" data-Templation="{{world}}">WORLD!</span>">WORLD!</span> how are <span class="Templation" title="<span class="Templation" title="{{world}}" data-Templation="{{world}}">WORLD!</span>" data-Templation="<span class="Templation" title="{{world}}" data-Templation="{{world}}">WORLD!</span>">WORLD!</span>