How can the use of placeholders in a template class be optimized to prevent unexpected output or formatting issues?
To optimize the use of placeholders in a template class and prevent unexpected output or formatting issues, it is important to properly escape the placeholders to avoid any unintended interpretation of special characters. This can be done by using htmlentities() or htmlspecialchars() functions to encode the placeholders before inserting them into the template.
class Template {
private $template;
public function __construct($template) {
$this->template = $template;
}
public function render($data) {
$output = $this->template;
foreach($data as $key => $value) {
$output = str_replace("{{" . $key . "}}", htmlentities($value), $output);
}
return $output;
}
}
// Example usage
$template = new Template("<h1>Hello, {{name}}!</h1>");
$data = ['name' => '<script>alert("XSS attack")</script>'];
echo $template->render($data);