Auto-detect escaping method (default to no escaping), learn some new boolean values

This commit is contained in:
dana 2016-07-29 23:08:56 -05:00
parent 999530151e
commit 0403b21af7
2 changed files with 51 additions and 11 deletions

View file

@ -56,20 +56,21 @@ JSON data can also be provided by file path or on standard input:
```
Normally, input data is [auto-escaped](http://twig.sensiolabs.org/doc/api.html)
for HTML before rendering, but this is configurable:
based on the template file extension (or disabled by default if using standard
input), but this is configurable:
```
% twigc -p 'html=<p>Hello!</p>' <<< '{{ html }}'
&lt;p&gt;Hello!&lt;/p&gt;
<p>Hello!</p>
% twigc -p 'html=<p>Hello!</p>' -e 'url' <<< '{{ html }}'
%3Cp%3EHello%21%3C%2Fp%3E
% twigc -p 'html=<p>Hello!</p>' -e 'html' <<< '{{ html }}'
&lt;p&gt;Hello!&lt;/p&gt;
% twigc -p 'html=<p>Hello!</p>' -e 'js' <<< '{{ html }}'
\x3Cp\x3EHello\x21\x3C\x2Fp\x3E
% twigc -p 'html=<p>Hello!</p>' -e 'false' <<< '{{ html }}'
<p>Hello!</p>
% twigc -p 'html=<p>Hello!</p>' -e 'url' <<< '{{ html }}'
%3Cp%3EHello%21%3C%2Fp%3E
```
By default, references in the template to undefined variables are silently

View file

@ -226,16 +226,55 @@ class DefaultCommand extends Command {
}
}
// Normalise auto-escape setting
// If no escape option was supplied, try to auto-detect
// (we could do this with Twig's 'filename' method, but i have some
// control over this)
if ( $escape === null ) {
$escape = true;
if ( substr($template, -5) === '.twig' ) {
$ext = pathinfo(substr($template, -5), \PATHINFO_EXTENSION);
} else {
$ext = pathinfo($template, \PATHINFO_EXTENSION);
}
switch ( strtolower($ext) ) {
case 'template':
case 'tmpl':
case 'tpl':
case 'htm':
case 'html':
case 'phtml':
case 'thtml':
case 'xhtml':
$escape = 'html';
break;
case 'css':
case 'scss':
$escape = 'css';
break;
case 'js':
$escape = 'js';
break;
default:
$escape = false;
break;
}
// Otherwise, try to parse the supplied method
} else {
// Normalise some boolean values
$escape = strtolower($escape);
$escape = $escape === 'f' ? 'false' : $escape;
$escape = $escape === 'n' ? 'false' : $escape;
$escape = $escape === 'none' ? 'false' : $escape;
$escape = $escape === 'never' ? 'false' : $escape;
$escape = $escape === 't' ? 'true' : $escape;
$escape = $escape === 'y' ? 'true' : $escape;
$escape = $escape === 'always' ? 'true' : $escape;
$bool = filter_var($escape, \FILTER_VALIDATE_BOOLEAN, \FILTER_NULL_ON_FAILURE);
if ( $bool !== null ) {
$escape = $bool;
} else {
$escape = strtolower($escape);
$escape = $bool ? 'html' : false;
}
}