定制 pug-php/pug-symfony 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

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

pug-php/pug-symfony

Composer 安装命令:

composer require pug-php/pug-symfony

包简介

Pug template engine for Symfony

README 文档

README

Latest Stable Version GitHub Actions StyleCI Test Coverage

Pug template engine for Symfony

This is the documentation for the ongoing version 3.0. Click here to load the documentation for 2.8

Install

In the root directory of your Symfony project, open a terminal and enter.

composer require pug-php/pug-symfony

When you are asked to install automatically needed settings, enter yes.

It for any reason, you do not can or want to use it, you will have to add to your config/bundles.php file:

Pug\PugSymfonyBundle\PugSymfonyBundle::class => ['all' => true],

Usage

Create Pug views by creating files with .pug extension in templates such as contact.pug:

h1
  | Contact
  =name

Then inject Pug\PugSymfonyEngine to call it in your controller:

namespace App\Controller;

use Pug\PugSymfonyEngine;
use Symfony\Component\HttpKernel\Attribute\AsController;
use Symfony\Component\Routing\Annotation\Route;

#[AsController]
class MyController
{
    #[Route('/contact')]
    public function contactAction(PugSymfonyEngine $pug)
    {
        return $pug->renderResponse('contact/contact.pug', [
            'name' => 'Us',
        ]);
    }
}

Or alternatively you can use \Pug\Symfony\Traits\PugRenderer to call directly ->render() from any method of a controller (or service):

namespace App\Controller;

use Pug\Symfony\Traits\PugRenderer;
use Symfony\Component\HttpKernel\Attribute\AsController;
use Symfony\Component\Routing\Annotation\Route;

#[AsController]
class MyController
{
    use PugRenderer;

    #[Route('/contact')]
    public function contactAction()
    {
        return $this->render('contact/contact.pug', [
            'name' => 'Us',
        ]);
    }
}

No matter if your controller extends AbstractController as it can also render twig views, so it will just work the same as before rather you ->render('view.html.twig') or ->render('view.pug').

Note: standard Twig functions are also available in your pug templates, for instance:

!=form(form)

As per https://symfony.com/doc/current/forms.html

Pass the FormView as usual from the controller:

$task = new Task();
// ...

$form = $this->createFormBuilder($task)
    // ...
    ->getForm();

return $pug->renderResponse('home.pug', [
    'form' => $form->createView(),
]);

Configure

You can inject Pug\PugSymfonyEngine to change options, share values, add plugins to Pug at route level:

// In a controller method
#[Route('/contact')]
public function contactAction(\Pug\PugSymfonyEngine $pug)
{
    $pug->setOptions(array(
      'pretty' => true,
      'pugjs' => true,
      // ...
    ));
    $pug->share('globalVar', 'foo');
    $pug->getRenderer()->addKeyword('customKeyword', $bar);

    return $pug->renderResponse('contact/contact.pug', [
        'name' => 'Us',
    ]);
}

If you use the PugRenderer trait, you don't need to inject the service again and can just use $this->pug.

Same can be run globally on a given event such as onKernelView to apply customization before any view rendering.

See the options in the pug-php documentation: https://phug-lang.com/#options

Initial options can also be passed in parameters in your config/services.yaml:

# config/services.yaml
parameters:
    # ...
    pug:
        expressionLanguage: php

Note: you can also create a config/packages/pug.yaml to store the Pug settings.

Globals of Twig are available in Pug views (such as the app variable to get app.token or app.environment) and any custom global value or service you will add to twig.yaml:

# config/packages/twig.yaml
twig:
    # ...
    globals:
        translator: '@translator'

Make the translator available in every view:

p=translator.trans('Hello %name%', {'%name%': 'Jack'})

Keys (left) passed to globals are the variable name to be used in the view, values (right) are the class name (can be '@\App\MyService') or the alias to resolve the dependency injection. It can also be static values such as ga_tracking: 'UA-xxxxx-x'.

If you need more advanced customizations to be applied for every Pug rendering, you can use interceptor services.

# config/services.yaml
parameters:
    # ...
    pug:
        interceptors:
            - App\Service\PugInterceptor
            # You can add more interceptors

services:
    # ...

    # They all need to be public
    App\Service\PugInterceptor:
        public: true

Then the interceptor would look like this:

// src/Service/PugInterceptor.php
namespace App\Service;

use Pug\Symfony\Contracts\InterceptorInterface;
use Pug\Symfony\RenderEvent;
use Symfony\Contracts\EventDispatcher\Event;

class PugInterceptor implements InterceptorInterface
{
    public function intercept(Event $event)
    {
        if ($event instanceof RenderEvent) {
            // Here you can any method on the engine or the renderer:
            $event->getEngine()->getRenderer()->addKeyword('customKeyword', $bar);
            $event->getEngine()->getRenderer()->addExtension(MyPlugin::class);

            // Or/and manipulate the local variables passed to the view:
            $locals = $event->getLocals();
            $locals['foo']++;
            $event->setLocals($locals);

            // Or/and get set the name of the view that is about to be rendered:
            if ($event->getName() === 'profile.pug') {
                // if user variable is missing
                if (!isset($event->getLocals()['user'])) {
                    $event->setName('search-user.pug');
                    // Render the search-user.pug instead of profile.pug
                }
            }
        }
    }
}

As services, interceptors can inject any dependency in their constructor to use it in the intercept method:

class PugInterceptor implements InterceptorInterface
{
    private $service;

    public function __construct(MyOtherService $service)
    {
        $this->service = $service;
    }

    public function intercept(Event $event)
    {
        if ($event instanceof RenderEvent) {
            $event->getEngine()->share('anwser', $this->service->getAnwser());
        }
    }
}

And interceptors are lazy-loaded, it means in the example above, neither PugInterceptor nor MyOtherService will be loaded if they are not used elsewhere and if the current request does not end with a pug rendering (pure-Twig view, API response, websocket, etc.) so it's a good way to optimize things you only need to do before pug rendering.

Deployment

In production, you better have to pre-render all your templates to improve performances using the command below:

php bin/console assets:publish --env=prod

Security contact information

To report a security vulnerability, please use the Tidelift security contact. Tidelift will coordinate the fix and disclosure.

pug-php/pug-symfony 适用场景与选型建议

pug-php/pug-symfony 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 4.41k 次下载、GitHub Stars 达 44, 最近一次更新时间为 2016 年 06 月 23 日, 在 PHP 生态内属于活跃度较高的组件。

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

围绕 pug-php/pug-symfony 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

  • 总下载量: 4.41k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 44
  • 点击次数: 2
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 44
  • Watchers: 3
  • Forks: 3
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2016-06-23