我想避免在我的视图中使用标记.然而,我很难加载页眉和页脚文件,因为它们以文本形式输出,而不是由PHP处理RequireOnce‘file’.我明白为什么会这样,但我不知道该怎么做.

controller/home.php

<?php

$params = [
   'page_title' => 'My Page Title'
];

renderView('/views/home.view.php', $params);

functions.php

function renderView($view, array $params = []): void
{
    $template = file_get_contents($view, FILE_USE_INCLUDE_PATH);

    foreach($params as $key => $value)
    {
        $template = str_replace('{{ ' . $key . ' }}', $value, $template);
    }

    echo $template;
}

/views/home.view.php

<?php require_once('header.view.php'); ?>

<main>Main content.</main>

<?php require_once('footer.view.php'); ?>

/views/header.view.php

<html>
<head>
<title>{{ page_title }}</title>
</head>
<body>

推荐答案

如果您想要替换页眉和页脚,则需要通过renderView()函数输出它们,而不是直接使用require_once.即,从主视图中删除对页眉/页脚的引用:

<main>Main content.</main>

并将它们移动到主控制器:

renderView('/views/header.view.php', $params);
renderView('/views/home.view.php', $params);
renderView('/views/footer.view.php', $params);

不过,您必须小心,您不希望将PHP源代码和可替换标记放在同一文件中.所以,你可能应该用not来命名你的观点,以*.php结尾.

Php相关问答推荐

PHP,ZipArchive删除一个空文件?

使用MySQLi使用连接字符串设置字符集

将WooCommerce WC_Order对象与wp_Schedule_Event一起使用

使用CODIGNITER3中的OR和AND子句进行查询

从WooCommerce订单项目获取Dokan卖家详细信息

dyld[45923]:未加载库:/usr/local/opt/libavif/lib/libavif.15dylib

服务器升级到新的mysql版本8.0.34后查询错误

我不明白为什么我收到未定义的数组键异常错误 - Laravel 9 PHP 8

图片上传成功

如何为自定义帖子类型的自定义角色提供功能

Shopware 6 AuthControllerDecorator已弃用

我需要一个正则表达式模式来获取在不包含特定字符串后面的模式中的文本

如何在PHP中对多个脚本调用进行排队?

为什么foreach循环会输出每个结果?

如何在自定义消息中包含 WooCommerce 选定的产品变体详细信息

如何获取用户之间的最新消息列表

MySQLI bind_param导致的Cannot modify readonly property错误

为什么在解压缩具有混合字符串和 int 键的关联数组时出现错误消息无法使用位置参数...?

PHP 中的 curl 验证失败(openssh 连接正常)

hasOne/belongsToMany 或多对多