charcoal/view
Composer 安装命令:
composer require charcoal/view
包简介
Charcoal View (templates rendering and tools)
README 文档
README
The View package provides an integration with Mustache and Twig for templating.
Installation
composer require charcoal/view
For Charcoal projects, the service provider can be registered from your configuration file:
{
"service_providers": {
"charcoal/view/service-provider/view": {}
}
}
Usage
It is a thin layer on top of various rendering engines, such as mustache or twig that can be used either as a View component with any frameworks, as PSR-7 renderer for such frameworks (such as Slim)
A View can be used to render any template (which can be loaded from the engine) with any object (or array, for twig) as context.
use Charcoal\View\Mustache\MustacheLoader; use Charcoal\View\Mustache\MustacheEngine; use Charcoal\View\GenericView; $loader = new MustacheLoader([ 'base_path' => __DIR__, 'paths' => [ 'templates', 'views', ], ]); $engine = new MustacheEngine([ 'loader' => $loader, ]); $view = new GenericView([ 'engine' => $engine, ]); echo $view->render('foo/bar/template', $context); // A template string can also be used directly, with `renderTemplate()` $str = 'My name is {{what}}'; echo $view->renderTemplate($str, $context);
Basic Usage, with service provider
All this bootstrapping code can be avoided by using the ViewServiceProvider. This provider expects a config object
use Pimple\Container; use Charcoal\View\ViewServiceProvider; $container = new Container([ 'base_path' => __DIR__, 'view' => [ 'default_engine' => 'mustache', 'paths' => [ 'views', 'templates', ], ], ]); $container->register(new ViewServiceProvider()); echo $container['view']->render('foo/bar/template', $context);
👉 The default view engine, used in those examples, would be mustache.
Using the Renderer, with Slim
A view can also be implicitely used as a rendering service. Using the provided view/renderer, with a PSR7 framework (in this example, Slim 3):
use Charcoal\View\ViewServiceProvider; use Slim\App; $app = new App(); $container = $app->getContainer(); $container->register(new ViewServiceProvider()); $app->get('/hello/{name}', function ($request, $response, $args) { // This will render the "hello" template return $this->renderer->render($response, 'hello', $args); }); $app->run();
Just like the view, it is possible to simply register all dependencies on a Pimple container (with the
ViewServiceProvider) to avoid all this bootstrapping code. The renderer is available as$container['view/renderer'].
Module components
The basic components in the View package are:
- View, which provide the basic interface to all components.
- Engine, to actually render the templates.
- Loader, to load template files.
- Viewable, which allow any object to be rendered with a View.
- Renderer, an extra helper to use a view to render into PSR-7 request/response objects.
Views
The Charcoal\View\ViewInterface defines all that is needed to render templates via a view engine:
render($templateIdent = null, $context = null)renderTemplate($templateString, $context = null)
The abstract class Charcoal\View\AbstractView fully implements the ViewInterface and adds the methods:
Generic view
As convenience, the \Charcoal\View\GenericView class implements the full interface by extending the AbstractView base class.
View Engines
Charcoal views support different templating Engines_, which are responsible for loading the appropriate template (through a loader) and render a template with a given context according to its internal rules. Every view engines should implement \Charcoal\View\EngineInterface.
There are 3 engines available by default:
mustache(default)phptwig
Mustache Helpers
Mustache can be extended with the help of helpers. Those helpers can be set by extending view/mustache/helpers in the container:
$container->extend('view/mustache/helpers', function(array $helpers, Container $container) { return array_merge($helpers, [ 'my_extended_method' => function($text, LambdaHelper $lambda) { if (isset($helper)) { $text = $helper->render($text); } return customMethod($text); }, ]); });
Provided helpers:
- Assets helpers:
purgeJsaddJsjsaddJsRequirementjsRequirementsaddCsspurgeCsscssaddCssRequirementcssRequirementspurgeAssets
- Translator helpers:
_tTranslate a string with{{#_t}}String to translate{{/_t}}
- Markdown helpers:
markdownParse markdown to HTML with{{#markdown}}# this is a H1{{/markdown}}
Twig Helpers
Twig can be extended with the help of TwigExtension. Those helpers can be set by extending view/twig/helpers in the container:
$container['my/twig/helper'] = function (Container $container): MyTwigHelper { return new MyTwigHelper(); }; $container->extend('view/twig/helpers', function (array $helpers, Container $container): array { return array_merge( $helpers, $container['my/twig/helper']->toArray(), ); });
Provided helpers:
- Debug helpers
debugfunction{{ debug() }}isDebugfunction alias ofdebug
- Translator helpers:
transfilter a string with{{ "String to translate"|trans }}transChoicefilter:{{ '{0}First: %test%|{1}Second: %test%'|transChoice(0, {'%test%': 'this is a test'}) }} {# First: this is a test #} {{ '{0}First: %test%|{1}Second: %test%'|transChoice(1, {'%test%': 'this is a test'}) }} {# Second: this is a test #}
- Url helpers:
baseUrlfunction{{ baseUrl() }}siteUrlfunction alias ofbaseUrlwithBaseUrlfunction{{ withBaseUrl('/example/path') }}
Loaders
A Loader service is attached to every engine. Its function is to load a given template content
Templates
Templates are simply files, stored on the filesystem, containing the main view (typically, HTML code + templating tags, but can be kind of text data).
- For the mustache engine, they are
.mustachefiles. - For the php engine, they are
.phpfiles. - For the twig engine, they are
.twigfiles.
Templates are loaded with template loaders. Loaders implement the Charcoal\View\LoaderInterface and simply tries to match an identifier (passed as argument to the load() method) to a file on the filesystem.
Calling $view->render($templateIdent, $context) will automatically use the engine's Loader object to find the template $templateIdent.
Otherwise, calling $view->renderTemplate($templateString, $context) expects an already-loaded template string as parameter.
Viewable Interface and Trait
Any objects can be made renderable (viewable) by implementing the Charcoal\View\ViewableInterface by using the Charcoal\View\ViewableTrait.
The interface adds the following methods to their implementing objects:
setTemplateIdent($ident)templateIdent()setView($view)view()render($templateIdent = null)renderTemplate($templateString)
Examples
Given the following classes:
use \Charcoal\View\ViewableInterface; use \Charcoal\View\ViewableTrait; class MyObject implements ViewableInterface { use ViewableTrait; public function world() { return 'world!'; } }
The following code:
$obj = new MyObject(); $obj->renderTemplate('Hello {{world}}');
would output: "Hello world!"
View Service Provider
As seen in the various examples above, it is recommended to use the ViewServiceProvider to set up the various dependencies, according to a config, on a Pimple container.
The Service Provider adds the following service to a container:
viewThe base view instance.view/rendererA PSR-7 view renderer.view/parsedownA parsedown service, to render markdown into HTML.
Other services / options are:
view/configView configuration options.view/engineCurrently used view engine.view/loaderCurrently used template loader.
The ViewServiceProvider expects the following services / keys to be set on the container:
configApplication configuration. Should contain a "view" key to build the ViewConfig obejct.
The View Config
Most service options can be set dynamically from a configuration object (available in $container['view/config']).
Example for Mustache:
{
"base_path":"/",
"view": {
"default_engine":"mustache",
"paths":[
"templates",
"views"
]
}
}
Example for Twig:
{
"view": {
"default_engine": "twig",
"use_cache": false,
"strict_variables": true,
"paths": [
"templates",
"views"
]
}
}
Resources
charcoal/view 适用场景与选型建议
charcoal/view 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 105 次下载、GitHub Stars 达 0, 最近一次更新时间为 2022 年 11 月 08 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「twig」 「mustache」 「view」 「templates」 「charcoal」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 charcoal/view 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 charcoal/view 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 charcoal/view 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Shoot aims to make providing data to your templates more manageable
This Symfony bundle integrates PhpSpreadsheet into Symfony using Twig.
A Twig extension to insert css as inline styles with a tag
Caching and compression for Twig assets (JavaScript and CSS).
Strongly opinionated MVC framework for rapid development
Twig extensions for Tracy Debugger
统计信息
- 总下载量: 105
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 9
- 依赖项目数: 5
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2022-11-08