Ahm*_*ger 11 php frameworks design-patterns blade
我想创建一个设计模式并使用"Blade templating engine".我可以在Laravel之外使用Blade模板引擎并在我的新模式中使用它吗?
mag*_*nes 22
作为记录:
我测试了许多库在Laravel之外运行刀片(我没有使用),并且大多数是原始库的糟糕黑客,只是复制并粘贴代码并删除了一些依赖关系,但它保留了很多Laravel的依赖关系.
所以我创建了(对于一个项目)刀片的替代品,它在一个文件中免费(MIT许可证,即关闭源/私有代码没问题)并且没有外部库的单一依赖.您可以下载该类并开始使用它,或者您可以通过composer安装.
https://github.com/EFTEC/BladeOne
https://packagist.org/packages/eftec/bladeone
它与100%兼容,没有Laravel自己的功能(扩展).
这个怎么运作:
<?php
include "lib/BladeOne/BladeOne.php";
use eftec\bladeone;
$views = __DIR__ . '/views'; // folder where is located the templates
$compiledFolder = __DIR__ . '/compiled';
$blade=new bladeone\BladeOne($views,$compiledFolder);
echo $blade->run("Test.hello", ["name" => "hola mundo"]);
?>
Run Code Online (Sandbox Code Playgroud)
另一种选择是使用树枝,但我测试了它,我不喜欢它.我喜欢Laravel的语法,它接近ASP.NET MVC Razor.
编辑:到目前为止(2018年7月),它实际上是唯一支持Blade 5.6没有Laravel的新功能的模板系统.;-)
小智 5
Matt Stauffer 创建了一个完整的存储库,向您展示如何直接在 Laravel 外部使用各种 Illuminate 组件。我建议遵循他的示例并查看他的源代码。
https://github.com/mattstauffer/Torch
这是在 Laravel 之外使用 Laravel Views 的 index.php
https://github.com/mattstauffer/Torch/blob/master/components/view/index.php
您可以围绕它编写一个自定义包装器,以便您可以像 Laravel 一样调用它
use Illuminate\Container\Container;
use Illuminate\Events\Dispatcher;
use Illuminate\Filesystem\Filesystem;
use Illuminate\View\Compilers\BladeCompiler;
use Illuminate\View\Engines\CompilerEngine;
use Illuminate\View\Engines\EngineResolver;
use Illuminate\View\Engines\PhpEngine;
use Illuminate\View\Factory;
use Illuminate\View\FileViewFinder;
function view($viewName, $templateData)
{
// Configuration
// Note that you can set several directories where your templates are located
$pathsToTemplates = [__DIR__ . '/templates'];
$pathToCompiledTemplates = __DIR__ . '/compiled';
// Dependencies
$filesystem = new Filesystem;
$eventDispatcher = new Dispatcher(new Container);
// Create View Factory capable of rendering PHP and Blade templates
$viewResolver = new EngineResolver;
$bladeCompiler = new BladeCompiler($filesystem, $pathToCompiledTemplates);
$viewResolver->register('blade', function () use ($bladeCompiler) {
return new CompilerEngine($bladeCompiler);
});
$viewResolver->register('php', function () {
return new PhpEngine;
});
$viewFinder = new FileViewFinder($filesystem, $pathsToTemplates);
$viewFactory = new Factory($viewResolver, $viewFinder, $eventDispatcher);
// Render template
return $viewFactory->make($viewName, $templateData)->render();
}
Run Code Online (Sandbox Code Playgroud)
然后您可以使用以下命令来调用它
view('view.name', ['title' => 'Title', 'text' => 'This is text']);
Run Code Online (Sandbox Code Playgroud)