Slide 28
Slide 28 text
htmlspecialchars
private function renderTemplate(
string $html,
array $params
): string
{
$replaceKey = [];
$replaceValue = [];
foreach ($params as $key => $value) {
$replaceKey[] = '/{{ ' . $key . ' }}/';
$replaceValue[] =
htmlspecialchars(
$value,
ENT_QUOTES ,
'UTF-8'
);
}
$replaceKey[] = '/{{ action }}/';
$replaceValue[] = 'index.php';
return preg_replace(
$replaceKey, $replaceValue, $html);
}
private func renderTemplate(html: String, params: Dictionary) ->
String {
let pattern = "\\{\\{ action \\}\\}"
let replace = "index.swift"
var html =
html.stringByReplacingOccurrencesOfString(pattern, withString: replace,
options: NSStringCompareOptions.RegularExpressionSearch, range: nil)
for (key, value) in params {
let pattern = "\\{\\{ " + key + " \\}\\}"
let replace = self.htmlspecialchars(value)
html =
html.stringByReplacingOccurrencesOfString(pattern, withString: replace,
options: NSStringCompareOptions.RegularExpressionSearch, range: nil)
}
return html;
}
private func htmlspecialchars(var html: String) -> String {
let replaceDef: Dictionary = [
"\"": """,
"'": "'",
"<": "<",
">": ">",
]
for (key, value) in replaceDef {
let pattern = key;
let replace = value;
html = html.stringByReplacingOccurrencesOfString(pattern, withString:
replace,
options: NSStringCompareOptions.RegularExpressionSearch, range: nil)
}
return html
}