rinart73/document-helper

CodeIgniter 4 库,允许更轻松地生成 HTML,尤其是在处理标题标签、脚本、样式和图片时

v1.0.0-beta 2023-02-09 19:54 UTC

This package is auto-updated.

Last update: 2024-09-05 10:18:05 UTC


README

Coverage Status

Document Helper 是一个 CodeIgniter 4 库,旨在简化 HTML 生成,尤其是在处理元标签、样式、脚本和图片时。

它受到了 OpenCart 和 WordPress 的重度启发。

功能

  • 在控制器中添加文档 titlemetalink 标签;在控制器和视图中添加 htmlbody 类。
  • 注册可能需要的脚本和样式。当您请求它们时,它们的依赖项会自动添加和排序。
  • 生成图像变体(用于 srcset 的调整大小版本,如 WebP 等替代图像类型)并同时渲染 img/picture

入门

先决条件

安装

安装通过 Composer 完成。

composer require rinart73/document-helper

建议配置

document 辅助程序和 Rinart73\DocumentHelper\Document 类添加到您的 Controllers/BaseController.php

namespace App\Controllers;

use Rinart73\DocumentHelper\Document;

abstract class BaseController extends Controller
{
    protected $helpers = ['document'];
    protected Document $document;

    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);

        $this->document = service('document');
        $this->registerDocumentLibraries();
        $this->initDocumentDefaults();
    }

    // Register styles and scripts that you **might** need
    protected function registerDocumentLibraries()
    {
        $this->document->registerScript('jquery', 'https://cdn.jsdelivr.net.cn/npm/jquery@3.6.3/dist/jquery.min.js', [], '3.6.3');
    }

    // Set default Document parameters for your pages
    protected function initDocumentDefaults()
    {
        $this->document
            ->setHtmlAttributes(['lang' => 'en-US'])
            ->setMeta('charset', 'utf-8')
            ->setMeta('viewport', 'width=device-width, initial-scale=1')
            ->setMeta('robots', 'index, follow')
            ->setTitleSuffix('| MyWebSite')
            ->addScripts('jquery');
    }

然后,将辅助函数添加到您的布局中:Views/layouts/layout-default.php

<!doctype html>
<html <?= document_html() ?>>
<head>
    <?= document_head() ?>
</head>
<body <?= document_body() ?>>
    <?= $this->renderSection('content') ?>
    
    <?= document_footer() ?>
</body>
</html>

然后,您将能够在控制器和视图中使用库提供的功能:Controllers/Articles.php

namespace App\Controllers;

class Articles extends BaseController
{
    public function index()
    {
        $this->document
            ->addBodyClasses('archive', 'archive--articles')
            ->setTitle('My articles')
            ->setMeta('description', 'Articles archive description');
    }
}

概述

有关更多示例,请参阅 examples

文档标签

$document = service('document');

$document
    ->setHtmlAttributes(['lang' => 'en-US'])
    ->setBodyAttributes(['class' => 'page-article'])
    ->setTitle('My article')
    ->setTitleSuffix('| WebSite')
    ->setMeta('charset', 'utf-8')
    ->setMeta('viewport', 'width=device-width, initial-scale=1')
    ->setMeta('description', 'My article description')
    ->setMeta('robots', 'index, follow')
    ->addLink('canonical', 'https://example.com/articles/my-article/')
    ->addLink('alternate', 'https://example.com/articles/my-article/', ['hreflang' => 'en'])
    ->addLink('alternate', 'https://example.ru/articles/translated-article/', ['hreflang' => 'ru']);

脚本和样式

$document = service('document');

$document
    ->registerStyle('library', 'assets/css/library.css', [], '1.1')
    ->registerScript('library', 'assets/js/library.js', [], '1.1');

$document->registerScript('core', 'assets/js/core.js', [], '1.1.2');

$document->registerScript('app-common', 'assets/js/app-common.js', ['core', 'library'], '1.2');

/**
 * Will add `library` and `core` styles and scripts before `app-common`.
 * By default scripts automatically request styles with the same handle but the feature can be turned off.
 */
$this->document->addScripts('app-common');

// add script tag with serialized data before the `app-common` script
$document->localizeScript('app-common', 'appCommonData', [
  'baseUrl' => base_url(),
  'errorGeneric' => lang('Common.errorGeneric')
]);

// add inline script with custom attributes in the script tag
$document
    ->registerInlineScript('my-inline', 'console.log("Hello world");', [], ['data-test' => '42'])
    ->addScripts('my-inline');

图片

$images = service('documentImages');

// generate img tag with width and height
$images->renderTag('uploads/my.jpg');

// img tag without width and height because it's an external resource
$images->renderTag('https://via.placeholder.com/640x360');

// set image defaults and enable WebP
$images->setAlternateTypes(IMAGETYPE_WEBP)
  ->setSrcsetWidths(1536, 1024, 768)
  ->setImgAttributes(['class' => 'img-fluid', 'loading' => 'lazy']);

/**
 * Will generate:
 * 1. Proportionally scaled JPEG versons with 1536px, 1024px and 768px widths
 * 2. WebP versions of the full size image and resized images
 * Will render a picture tag with sources and img inside
 * By default images are generated on-demand but this behaviour can be altered.
 */
$images->renderTag('uploads/my.jpg');

/**
 * Will generate:
 * 1. 1024x1024 and 768x768 versions of the image. If image needs to be cut,
 * data in the top right corner will be prioritised.
 * 2. WebP versions of the resized images
 * Will render a picture tag with sources and img inside (won't include original file),
 * Default class attribute will be overridden but loading=lazy will be kept.
 */
$images->renderTag('uploads/my.jpg', ['1:1', 'top-right', 1024, 768], ['class' => 'img-square']);

辅助程序

辅助函数通常用于视图内部,尽管它们也可以用于其他任何地方。

Controllers/YourController.php

class YourController extends BaseController
{
    public function index()
    {
        helper('document');
    }
}

Views/layout-default.php

<!doctype html>
<html <?= document_html() ?>>
<head>
    <?= document_head() ?>
</head>
<body <?= document_body() ?>>
    <?= $this->renderSection('content') ?>
    
    <?= document_footer() ?>
</body>
</html>

Views/view-auth.php

<?= $this->extend('layout-default') ?>

<?php
document_add_html_classes('h-100');
document_add_body_classes('bg-light', 'h-100', 'page-auth');
document_add_libraries('bootstrap', 'app-auth');
?>

<?= $this->section('content') ?>

<main class="container-xl h-100">
    <div class="row h-100 align-items-center justify-content-center">
        <div class="col">
            <?= document_image('uploads/my.jpg', ['1:1', 'top-right', 1024, 768], ['class' => 'img-square']) ?>
        </div>
    </div>
</main>

<?= $this->endSection() ?>

许可证

本项目采用 MIT 许可证 - 有关详细信息,请参阅 LICENSE 文件。