akram-zaitout/laravel-katex 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

akram-zaitout/laravel-katex

Composer 安装命令:

composer require akram-zaitout/laravel-katex

包简介

A comprehensive Laravel package for rendering beautiful mathematical expressions using KaTeX

README 文档

README

Laravel KaTeX Package Logo

Latest Version on Packagist Total Downloads License

A comprehensive, production-ready Laravel package for rendering beautiful mathematical expressions using KaTeX. Native PHP implementation with dependency injection, following Laravel best practices.

✨ Features

  • Flexible & Intuitive - Use it your way with Blade directives, components, or our Facade—whatever fits your coding style.
  • 🔒 Secure by Design - We handle XSS protection and validation automatically so you can render user content with peace of mind.
  • ⚙️ Fully Customizable - Tweak delimiters, error handling, and macros globally or on the fly to match your specific needs.
  • 🚀 Blazing Fast - Optimized rendering ensures your mathematical expressions load instantly without slowing down your app.
  • 🧪 Production Ready - Built with a comprehensive test suite and strict typing to ensure reliability in mission-critical applications.

📋 Requirements

  • PHP 7.2 or higher
  • Laravel 6.0 or higher
  • ext-json

📦 Installation

Install the package via Composer:

composer require akram-zaitout/laravel-katex

Publish Configuration (Optional)

php artisan vendor:publish --tag=katex-config

This creates config/katex.php where you can customize all aspects of the package.

Publish Views (Optional)

php artisan vendor:publish --tag=katex-views

🚀 Quick Start

Basic Setup

In your Blade layout file (e.g., resources/views/layouts/app.blade.php):

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>My Application</title>
    
    @katexStyles
</head>
<body>
    @yield('content')
    
    @katexScripts
</body>
</html>

Using Blade Directives

{{-- Inline math --}}
<p>The quadratic formula is @katex('x = \frac{-b \pm \sqrt{b^2-4ac}}{2a}')</p>

{{-- Display (block) math --}}
@katexBlock('\int_{-\infty}^{\infty} e^{-x^2} dx = \sqrt{\pi}')

{{-- With variables --}}
@php
    $equation = 'E = mc^2';
@endphp
<p>Einstein's equation: @katex($equation)</p>

📖 Usage

1. Blade Directives

@katexStyles

Renders the KaTeX CSS stylesheet:

@katexStyles

@katexScripts

Renders KaTeX JavaScript with optional configuration:

{{-- Default options --}}
@katexScripts

{{-- Custom options --}}
@katexScripts([
    'delimiters' => [
        ['left' => '$', 'right' => '$', 'display' => false],
        ['left' => '$$', 'right' => '$$', 'display' => true],
    ],
    'throwOnError' => false,
    'macros' => [
        '\\RR' => '\\mathbb{R}',
    ]
])

@katex

Renders inline mathematical expressions:

@katex('a^2 + b^2 = c^2')

@katexBlock

Renders display mode (block) mathematical expressions:

@katexBlock('\sum_{i=1}^{n} i = \frac{n(n+1)}{2}')

2. Facade

Use the Katex facade for programmatic access:

use AkramZaitout\LaravelKatex\Facades\Katex;

// Generate stylesheet
$styles = Katex::generateStylesheet();

// Generate scripts
$scripts = Katex::generateScripts(['throwOnError' => false]);

// Wrap expressions
$inline = Katex::wrapInline('x^2');
$display = Katex::wrapDisplay('\int_0^\infty');

// Get configuration
$version = Katex::getConfig('version');

3. Helper Functions

// Get renderer instance
$renderer = katex();

// Render inline math
$inline = katex_inline('a^2 + b^2 = c^2');

// Render display math
$display = katex_display('\sum_{i=1}^{n} i');

// Generate assets
$styles = katex_styles();
$scripts = katex_scripts(['throwOnError' => false]);

4. Blade Component

<x-katex::math 
    expression="x^2 + y^2 = r^2" 
    display="false"
    class="my-math"
    id="pythagorean"
/>

5. Service Injection

use AkramZaitout\LaravelKatex\Services\KatexRenderer;

class MathController extends Controller
{
    public function __construct(
        protected KatexRenderer $katex
    ) {}
    
    public function show()
    {
        $expression = $this->katex->wrapInline('E=mc^2');
        
        return view('math.show', compact('expression'));
    }
}

⚙️ Configuration

Environment Variables

Set these in your .env file:

KATEX_VERSION=0.16.28
KATEX_CDN=https://cdn.jsdelivr.net/npm/katex
KATEX_CSS_INTEGRITY=sha384-Wsr4Nh3yrvMf2KCebJchRJoVo1gTU6kcP05uRSh5NV3sj9+a8IomuJoQzf3sMq4T
KATEX_JS_INTEGRITY=sha384-+W9OcrYK2/bD7BmUAk+xeFAyKp0QjyRQUCxeU31dfyTt/FrPsUgaBTLLkVf33qWt
KATEX_AUTO_RENDER_INTEGRITY=sha384-hCXGrW6PitJEwbkoStFjeJxv+fSOOQKOPbJxSfM6G5sWZjAyWhXiTIIAmQqnlLlh

Configuration File

Publish and edit config/katex.php:

return [
    'version' => '0.16.28',
    'cdn' => 'https://cdn.jsdelivr.net/npm/katex',
    
    'options' => [
        'delimiters' => [
            ['left' => '$$', 'right' => '$$', 'display' => true],
            ['left' => '\\(', 'right' => '\\)', 'display' => false],
        ],
        'throwOnError' => false,
        'errorColor' => '#cc0000',
        'macros' => [
            '\\RR' => '\\mathbb{R}',
            '\\NN' => '\\mathbb{N}',
        ],
    ],
];

🌍 Local Asset Management (Offline Support)

This package supports downloading KaTeX assets to your local application, allowing you to run without external CDN dependencies. This is perfect for offline environments, intranets, or strict privacy compliance/GDPR.

1. Download Assets

Run the artisan command to download CSS, JS, and font files to public/vendor/katex:

php artisan katex:download

You can also specify a specific version:

php artisan katex:download --version=0.16.0

2. Enable Local Assets

Update your .env file to tell the package to use the local files:

KATEX_USE_LOCAL_ASSETS=true

Or configure it in config/katex.php:

'use_local_assets' => true,

🎓 Examples

<article class="lesson">
    <h1>Calculus Fundamentals</h1>
    
    <p>The derivative of @katex('x^n') is @katex('nx^{n-1}').</p>
    
    <h2>Example</h2>
    @katexBlock('\frac{d}{dx}(x^3) = 3x^2')
    
    <h2>The Power Rule</h2>
    @katexBlock('\frac{d}{dx}(x^n) = nx^{n-1}')
</article>

🔒 Security

XSS Protection

All user input is automatically escaped using Laravel's e() helper:

{{-- Safe: HTML is escaped --}}
@katex($userInput)

Subresource Integrity

SRI hashes ensure CDN files haven't been tampered with:

'css_integrity' => 'sha384-Wsr4Nh3yrvMf2KCebJchRJoVo1gTU6kcP05uRSh5NV3sj9+a8IomuJoQzf3sMq4T',

Trust Settings

By default, \url and \href commands are disabled. Enable only if needed:

'options' => [
    'trust' => false, // Keep disabled for user-generated content
],

📝 License

This package is open-sourced software licensed under the MIT license.

Made with ❤️ by Akram Zaitout

akram-zaitout/laravel-katex 适用场景与选型建议

akram-zaitout/laravel-katex 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 7 次下载、GitHub Stars 达 1, 最近一次更新时间为 2026 年 01 月 28 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「math」 「latex」 「laravel」 「Rendering」 「mathematics」 「blade」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 akram-zaitout/laravel-katex 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 akram-zaitout/laravel-katex 我们能提供哪些服务?
定制开发 / 二次开发

基于 akram-zaitout/laravel-katex 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 7
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 1
  • 点击次数: 24
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 1
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2026-01-28