【问题标题】:How to minify view HTML in Codeigniter 4 (CI 4)如何在 Codeigniter 4 (CI 4) 中缩小视图 HTML
【发布时间】:2020-09-23 10:34:20
【问题描述】:

我知道我们可以通过钩子在 CI3 中缩小 HTML,但在 CI 4 中

我通过在返回每个方法之前添加一个缩小函数来做到这一点。

    minifyHTML(view('admin/template/template',$this->data));

还有什么其他方法可以在不到处使用 minify 函数的情况下做到这一点?

我还想出了另一个解决方案,即在 BaseConroller 中添加一个模板函数来呈现所有视图。但是我已经在项目的许多地方使用了 view() ,这对我来说不可行,但可以为其他人工作。

【问题讨论】:

  • 你不能让那个函数接收视图名称和数据而不是渲染视图并使用它吗?所以你的代码就像 minifyView('admin/template/template', $this->data);
  • 是的,没错,但问题是项目几乎准备就绪,因此无法更改所有项目文件。我在问题中已经提到的类似解决方案感谢您的回复
  • 在这种情况下,您需要扩展核心类。我会为你起草一份答复。

标签: codeigniter codeigniter-4


【解决方案1】:

在 CodeIgniter4 中,您可以使用事件来缩小输出(而不是像我们在 CodeIgniter3 中那样使用 Hooks),方法是在 app/Config/Events.php 文件中添加以下代码

//minify html output on codeigniter 4 in production environment
Events::on('post_controller_constructor', function () {

  if (ENVIRONMENT !== 'testing') {
while (ob_get_level() > 0)
{
    ob_end_flush();
}

ob_start(function ($buffer) {
    $search = array(
        '/\n/',      // replace end of line by a <del>space</del> nothing , if you want space make it down ' ' instead of ''
        '/\>[^\S ]+/s',    // strip whitespaces after tags, except space
        '/[^\S ]+\</s',    // strip whitespaces before tags, except space
        '/(\s)+/s',    // shorten multiple whitespace sequences
        '/<!--(.|\s)*?-->/' //remove HTML comments
    );

    $replace = array(
        '',
        '>',
        '<',
        '\\1',
        ''
    );

    $buffer = preg_replace($search, $replace, $buffer);
    return $buffer;
    });

  }

});

见https://gitlab.irbidnet.com/-/snippets/3

【讨论】:

  • 在 event.php 中添加了上述代码,但无法正常工作。还有什么需要做的吗?
【解决方案2】:

您需要扩展核心系统类才能在系统范围内执行此操作。

每次 CodeIgniter 运行时,都会有几个基类作为核心框架的一部分自动初始化。但是,可以将任何核心系统类与您自己的版本交换,甚至只是扩展核心版本。

您可以扩展的两个类是这两个:

  • CodeIgniter\View\View
  • CodeIgniter\View\Escaper

例如,如果您想使用一个新的 App\Libraries\View 类来代替核心​​系统类,则可以这样创建您的类:

类声明必须继承父类。

<?php namespace App\Libraries;

use CodeIgniter\View\View as View;

class View implements View
{
     public function __construct()
     {
         parent::__construct();
     }
}

您的类中与父类中的方法同名的任何函数都将被使用,而不是使用本地函数(这称为“方法覆盖”)。这允许您大幅更改 CodeIgniter 核心。

因此,在这种情况下,您可以查看系统视图类,然后将其更改为返回已压缩的输出。

在您的情况下,您甚至可以添加一个额外的参数,以便视图函数可以返回压缩或不压缩的输出。

有关在 CodeIgniter 4 中扩展核心类的更多信息,请阅读以下内容:

https://codeigniter.com/user_guide/extending/core_classes.html#extending-core-classes

【讨论】:

    猜你喜欢
    • 2021-01-10
    • 1970-01-01
    • 2021-12-27
    • 1970-01-01
    • 2014-04-08
    • 1970-01-01
    • 1970-01-01
    • 2021-07-18
    • 2020-06-01
    相关资源
    最近更新 更多