Laravel动态包含带值模板报错,如何正确实现动态引入?
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

