模板继承和没有Blade语法的部分

PHP*_*Pst 9 php templates laravel blade laravel-5

如何在不使用刀片的情况下构建视图层次 什么是刀片指令(I,E的纯PHP同行@section,@extend等等)?

也许,类似的东西 <?php extend('foo') ?>

在Phalcon框架中,虽然它有自己的模板引擎(Volt),但它的所有模板引擎也都以纯PHP语法提供.

luk*_*ter 7

由于Blade指令只是编译为普通的PHP,因此技术上可以使用视图结构化功能而无需实际使用Blade.我认为这不是很漂亮,我个人会对这个决定三思而后行.

您可以在此类中找到所有PHP代码,Blade编译为:

Illuminate\View\Compilers\BladeCompiler

这里是其中的一些:

@section('content')

<?php $__env->startSection('content'); ?>
Run Code Online (Sandbox Code Playgroud)

@endsection

<?php $__env->stopSection(); ?>
Run Code Online (Sandbox Code Playgroud)

@extends('layout')

这有点棘手.通常Blade会对其进行编译,然后将其添加到底部打印的页脚变量中.所以不要把它放在顶部(就像你想的那样@extends),你必须将它放在视图的末尾:

<?php echo $__env->make('layout', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>
Run Code Online (Sandbox Code Playgroud)

@yield('content')

<?php echo $__env->yieldContent('content'); ?>
Run Code Online (Sandbox Code Playgroud)


小智 6

要以纯PHP方式使用它,你必须检查storage/framework/cache/views并看看那里发生了什么.基本上,是Blade 编译为PHP代码(而不是使用@和正确的函数调用).

我能想到的一种方法是:

在您使用的模板中yield:

<!-- template.php -->
<div class="container">
    <!-- instead of using yield('container') -->
    <?php echo "_yield:container"; ?>
</div>
Run Code Online (Sandbox Code Playgroud)

在您的文件中,而不是使用sectionstop

<!-- view.php -->
<!-- instead of using extend('template') -->
<?php $templatePath = 'template.php'; ?>
<?php $sections = []; ?>
<!-- instead of using section('container') -->
<?php $currentSectionName = 'container'; ob_start(); ?>
    <p>This will be in my container div</p>
<!-- instead of using stop -->
<?php
    // get the current html
    $sections["_yield:".$currentSectionName] = ob_get_contents();
    ob_end_clean();
    ob_start();
    require($templateName);
    $template = ob_get_contents();
    ob_end_clean();
    echo str_replace($template,array_keys($sections),array_values($sections));
?>
Run Code Online (Sandbox Code Playgroud)

当然,这种方法充其量只是简单化.提供的代码不是复制和粘贴解决方案,更像是概念.

其他一切都很简单:

@foreach($arr as $k=>$v)
    ...
@endforeach
Run Code Online (Sandbox Code Playgroud)

翻译成

<?php foreach($arr as $k=>$v) : ?>
    ...
<?php endforeach; ?>
Run Code Online (Sandbox Code Playgroud)

这就是BladeCompiler的完成方式.同样是ifwhile.


Zar*_*hus -1

Blade每次都会编译成PHP,编译后的内容存储在storage/framework/views/*

以下链接是 Blade 可以编译的所有内容的列表,您应该能够从中提取一些知识:

https://github.com/Illuminate/view/blob/master/Compilers/BladeCompiler.php

大多数模板引擎的总体思路是它们像这样构建代码:

if ($condition):
  // do stuff
endif;

while ($condition):
  // do stuff
endwhile;

foreach ($array as $key => $value):
  // do stuff
endforeach;
Run Code Online (Sandbox Code Playgroud)

有关更多参考,请参阅https://secure.php.net/manual/en/control-structs.alternative-syntax.php