PHP code example of yangweijie / think-stempler

1. Go to this page and download the library: Download yangweijie/think-stempler library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

yangweijie / think-stempler example snippets


// config/view.php
return [
    'type' => 'Stempler',
    'view_path' => app()->getRootPath() . 'view' . DIRECTORY_SEPARATOR,
    'cache_path' => app()->getRuntimePath() . 'temp' . DIRECTORY_SEPARATOR,
    'view_suffix' => '.dark.php',
    'tpl_cache' => true,
    
    // Stempler 特性开关
    'enable_layout' => true,
    'enable_stack' => true,
    'enable_component' => true,
];

// 在控制器或服务中
$engine = app('view')->getEngine();
$engine->registerComponent('my-component', function($attributes, $content) {
    return "<div class='my-component'>{$content}</div>";
});


namespace app\controller;

use think\Controller;

class Index extends Controller
{
    public function index()
    {
        $data = [
            'title' => '首页',
            'users' => [
                ['name' => '张三', 'email' => '[email protected]'],
                ['name' => '李四', 'email' => '[email protected]'],
            ]
        ];
        
        return view('index', $data);
    }
}

public function profile()
{
    $user = $this->getUser();
    
    return view('user/profile', [
        'user' => $user,
        'pageTitle' => '个人资料',
        'breadcrumbs' => ['首页', '用户中心', '个人资料']
    ]);
}

// config/view.php
return [
    'type' => 'Stempler',
    'component_path' => app()->getRootPath() . 'view/components/',
    // 其他配置...
];

// 禁用某些功能
return [
    'type' => 'Stempler',
    'enable_layout' => true,   // 布局继承
    'enable_stack' => true,    // 栈系统
    'enable_component' => false, // 组件系统(如果不需要)
];

return [
    'type' => 'Stempler',
    'tpl_cache' => true,
    'cache_path' => app()->getRuntimePath() . 'temp/',
];

return [
    'type' => 'Stempler',
    'tpl_cache' => true,
    'view_debug' => false,
    'strip_space' => true, // 移除多余空白
];

return [
    'type' => 'Stempler',
    'view_debug' => true,
];

$engine = app('view')->getEngine();
$compiled = $engine->compile($templateContent, $templateFile);
echo $compiled;
html
@foreach($users as $user)
    <div class="user">
        <h3>{{ $user->name }}</h3>
        <p>{{ $user->email }}</p>
    </div>
@endforeach

@for($i = 1; $i <= 10; $i++)
    <span>{{ $i }}</span>
@endfor

@while($condition)
    <!-- 循环内容 -->
    @break
    @continue
@endwhile
html
<!-- JSON 输出 -->
<script>
    var config = @json($config);
    var users = @json($users);
</script>

<!-- PHP 代码 -->
@php
    $computed = $price * $quantity;
    $total = number_format($computed, 2);
@endphp
<p>总计: {{ $total }}</p>