Skip to content

Instantly share code, notes, and snippets.

@devgaucho
Created December 31, 2023 01:41
Show Gist options
  • Save devgaucho/f17b27dffacf25eae0da5fdf9cf821cf to your computer and use it in GitHub Desktop.
Save devgaucho/f17b27dffacf25eae0da5fdf9cf821cf to your computer and use it in GitHub Desktop.
function chaplin(str,data) {
// {{#nome_da_variavel}} ... {{/nome_da_variavel}}
const blockPattern=/{{#([a-zA-Z0-9_]+)}}(.*?){{\/\1}}/gs;
// {&nome_da_variavel}} ou {{nome_da_variavel}}
const variablePattern=/{{(?:&)?([a-zA-Z0-9_]+)}}/g;
// função pra escapar o html
var escapeHtml=function(str) {
const htmlEntities={
'&': '&',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#39;'
};
return str.replace(/[&<>"']/g,function(match){
return htmlEntities[match];
});
};
// renderiza os blocos
var fnBlock=function(match,blockName,blockContent){
var dataIsArray=Array.isArray(data[blockName]);
if(data[blockName]!==undefined && dataIsArray){
// processa o bloco para cada variável
let blockResult='';
data[blockName].forEach(function(item){
blockResult+=chaplin(blockContent,item);
});
return blockResult;
} else {
// remove o bloco se ele não existe
return '';
}
};
str=str.replace(blockPattern,fnBlock);
// renderiza as variáveis simples
var fnVar=function(match,variableName){
const value=data[variableName];
if(value!==undefined){
if(match.startsWith('{{&')){
return value;
}else{
return escapeHtml(value);
}
}else{
return match;
}
};
str=str.replace(variablePattern,fnVar);
return str;
}
<?php
namespace gaucho;
class chaplin{
function render($str,$data){
return $this->renderFromString($str,$data);
}
function renderFromString($str,$data){
// {{#nome_da_variavel}} ... {{/nome_da_variavel}}
$blockPattern='/{{#([a-zA-Z0-9_]+)}}(.*?){{\/\1}}/s';
// {{&nome_da_variavel}} ou {{nome_da_variavel}}
$variablePattern='/{{(?:&)?([a-zA-Z0-9_]+)}}/';
// renderiza os loops
$fnLoop=function($matches) use ($data) {
$blockName=$matches[1];
$blockContent=$matches[2];
if(
isset($data[$blockName]) AND
is_array($data[$blockName])
){
// processa para cada variável
$blockResult='';
foreach($data[$blockName] as $item){
$blockResult.=$this->render(
$blockContent,$item
);
}
return $blockResult;
} else {
// remove o bloco se ele não existe
return '';
}
};
$str=preg_replace_callback(
$blockPattern,$fnLoop,$str
);
// renderiza as variáveis simples
$fnVar=function($matches) use ($data){
$variableName=$matches[1];
if(isset($data[$variableName])){
$value=$data[$variableName];
}else{
$value=$matches[0];
}
if(strpos($matches[0],'{{&')===0){
return $value;
}else{
return htmlspecialchars($value);
}
};
$str=preg_replace_callback(
$variablePattern,$fnVar,$str
);
return $str;
}
function renderFromFile($filename,$data){
if(file_exists($filename)){
$template=file_get_contents($filename);
return $this->renderFromString(
$template,$data
);
}else{
die(htmlentities($filename).' not found');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment