You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel动态包含带值模板报错,如何正确实现动态引入?

Fixing Dynamic Template Includes in Laravel Blade

Hey there! I get it—you’re trying to pull in a theme-specific header template dynamically, but that @include('{{ site('theme') }}.header') syntax is throwing errors. Let’s sort this out quickly.

Why Your Original Code Fails

Blade’s @include directive expects a string representing the template path, not output syntax ({{ }}). Those double handlebars are meant to print values directly to the browser, not pass them as arguments to Blade directives. That’s why even though {{ site('theme') }} outputs test, wrapping it in quotes and handlebars inside @include doesn’t work—it’s treating the whole {{ site('theme') }}.header as a literal string instead of parsing the dynamic value.

The Correct Approaches

1. Directly Use the Function in @include

You can pass the result of site('theme') directly, concatenate the .header suffix, and Blade will parse it correctly:

@include(site('theme') . '.header')

When site('theme') returns test, this resolves to @include('test.header'), which points to resources/views/test/header.blade.php—exactly what you want.

2. Store the Theme in a Variable (For Clarity)

If you need to reuse the theme value elsewhere in your template, it’s cleaner to store it first:

@php
    $activeTheme = site('theme');
@endphp

@include($activeTheme . '.header')

This way, you avoid repeating the site('theme') call and make your code a bit more readable.

Quick Check to Avoid Other Errors

Make sure your template file actually exists at the path Blade is looking for! For a theme value of test, the file should be located at:
resources/views/test/header.blade.php
If the path or filename is wrong (case matters on some servers!), you’ll still get an include error even with the correct syntax.

内容的提问来源于stack exchange,提问作者Rickin Rathatha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 07:49:25