やりたいこと
- Smartyのデフォルトエスケープ機能を有効にした状態($smarty->escape_html = true;)で、改行をBRタグに変換したい。(nl2brは効かない)
- nofilterは使いたくない。
環境
Smarty 3.1.21
やり方
Smarty_Internal_Compile_Private_Print_Expression#compile()内で、htmlspecialchars後にnl2brする属性を追加する。
変更箇所
「Smarty/libs/sysplugins/smarty_internal_compile_private_print_expression.php」の32行目あたりに、
「$option_flags」に「nl2br_filter」と「nl2br_xhtml_filter」を追加する。
1 |
public $option_flags = array('nocache', 'nofilter'); |
↓
1 |
public $option_flags = array('nocache', 'nofilter', 'nl2br_filter', 'nl2br_xhtml_filter'); |
同じく「smarty_internal_compile_private_print_expression.php」の79行目あたりに、
htmlspecialchars()の後にnl2br()する処理を入れる。
1 2 3 4 |
// autoescape html if ($compiler->template->smarty->escape_html) { $output = "htmlspecialchars({$output}, ENT_QUOTES, '" . addslashes(Smarty::$_CHARSET) . "')"; } |
↓
1 2 3 4 5 6 7 8 9 10 11 12 |
if ($compiler->template->smarty->escape_html) { if ($_attr['nl2br_filter']) { //改行を <br> に変換する用 $output = "nl2br(htmlspecialchars({$output}, ENT_QUOTES, '" . addslashes(Smarty::$_CHARSET) . "'), false)"; } elseif ($_attr['nl2br_xhtml_filter']) { //改行を <br /> に変換する用 $output = "nl2br(htmlspecialchars({$output}, ENT_QUOTES, '" . addslashes(Smarty::$_CHARSET) . "'), true)"; } else { // autoescape html $output = "htmlspecialchars({$output}, ENT_QUOTES, '" . addslashes(Smarty::$_CHARSET) . "')"; } } |
使い方
変数「$hoge」内の改行を「<br>」に変換したい場合。
1 |
{$hoge nl2br_filter} |
変数「$fuga」内の改行を「<br />」に変換したい場合。
1 |
{$fuga nl2br_xhtml_filter} |