我正在使用 php 版本 7.4.16、slim 4 和 twig ^3.2 创建博客。问题是我的变量是作为字符串插入的,而不是作为 html 标记的一部分
Структура проетка
> templates:
> base.twig
> home.twig
> index.php
home.twig 内容
<div> Lorem <div>
base.twig 内容
<!DOCTYPE html>
<html lang="en">
<head>
<title> {{ title }} </title>
</head>
<body>
{{ content }}
</body>
</html>
在 index.php 我正在执行代码
<?php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;
require __DIR__ . '/vendor/autoload.php';
$app = AppFactory::create();
$app->get('/', function (Request $request, Response $response, $args) use($view) {
$loader = new \Twig\Loader\FilesystemLoader('templates');
$twig = new \Twig\Environment($loader, [
'cache' => 'cache',
]);
$home = file_get_contents ('templates/home.twig'); // получаю содержимое из home.twig
echo $twig->render('base.twig', ['title' => 'home', 'content' => $home ]); // тут я вставляю в перемнную content содержимое $home
return $response;
});
$app->run();
请告诉我如何解决这个问题?
Twig 默认转义所有输出。要按原样显示数据,请使用过滤器
raw
:需要默认转义,这样一些人就不会因为 tweek 而抱怨他们得到某种 XSS。
此外,您可以在创建类的对象时将其设置为一个
false
选项autoescape
Environment
,但这又是不安全的,因为在这种情况下,通常所有输出变量都将按原样显示,这增加了 XSS 的机会。Twig 支持布局 - 这就是您所需要的
base.twig
像这样重写:home.twig
所以:所以
index.php
: