tesonet / react-js-twig
该库简化了使用 ReactJs 和 Twig 进行服务器端渲染
0.1.0
2016-11-29 21:10 UTC
Requires
- reactjs/react-php-v8js: ^2.0
- twig/twig: ~1.20
This package is not auto-updated.
Last update: 2024-09-14 19:58:45 UTC
README
该库简化了使用 ReactJs 和 Twig 进行服务器端渲染。
先决条件
该库使用 v8js php 扩展进行服务器端渲染。因此,为了使用此库,您必须 安装 v8js
依赖项
- Composer
- PHP >= 5.6
- V8Js php 扩展
使用方法
1) 运行 composer require tesonet/react-js-twig
2) 创建扩展并将其添加到 twig
use Tesonet\ReactJsTwig\TwigExtension; // create the extension $reactExtension = new TwigExtension(); // add it to twig $twig->addExtension($reactExtension); // allow access to the filesystem loader $reactExtension->setLoader($view->getLoader());
3) 设置错误处理器(可选)
默认情况下,在服务器端渲染过程中遇到的任何错误都会被重新抛出。有时,您可能希望在浏览器中调试错误。
为此,可以像这样覆盖默认的错误处理器
$reactExtension = new TwigExtension(); $reactExtension->setErrorHandler(function () { // do nothing });
4) 在模板中使用它
{% set reactConfiguration = { 'sourcePath': './path/to/assets/file.js', 'componentName': 'MyComponentName', 'props': { 'name': 'My prop has a name!' }, 'where': '#container' } %} {% spaceless %} <div id="{{ reactConfiguration.where | slice(1) }}"> {{ reactGenerateMarkup(reactConfiguration) }} </div> {% endspaceless %} <script src="/server/url/of/assets/file.js"></script> <script>{{ reactGenerateJavascript(reactConfiguration) }}</script>
5) 使用缓存(可选)
如果您想缓存生成的标记,我们强烈建议使用 asm89/twig-cache-extension 包。
一旦添加了之前提到的缓存扩展,请将 reactGenerateMarkup
调用包裹在缓存块中,如下所示
{% set reactConfiguration = { 'sourcePath': './path/to/assets/file.js', 'componentName': 'MyComponentName', 'props': { 'name': 'My prop has a name!' }, 'where': '#container' } %} {% spaceless %} <div id="{{ reactConfiguration.where | slice(1) }}"> {% cache 'markup' reactConfiguration %} {{ reactGenerateMarkup(reactConfiguration) }} {% endcache %} </div> {% endspaceless %} <script src="/server/url/of/assets/file.js"></script> <script>{{ reactGenerateJavascript(reactConfiguration) }}</script>