Blade Templates
- Introduction
- Complete Example and Syntax Boundaries
- Displaying Data
- Blade Directives
- Forms
- Components
- Layouts Using Template Inheritance
- Stacks
- Directive Reference
- Rendering Templates From Strings
- Differences From Laravel
Complete Example and Syntax Boundaries
Build the typed controller/view example, then the complete blog forms. Both include file paths, model types, route registration, and the generated layout requirements.
Use the syntax matching the file extension:
| Operation | .blade.html | .cshtml |
|---|---|---|
| Escaped text | {{ Model.Title }} | @Model.Title |
| Named route | {{ Route('posts.index') }} | @Route("posts.index") |
| Old input | {{ Old('Title') }} | @Old("Title") |
| CSRF field | @csrf | @Csrf() |
| PUT field | @method('PUT') | @Method("PUT") |
| Framework HTML helper | {{ Live.Scripts() }} | @Live.Scripts() |
| Loop | @foreach (...) ... @endforeach | @foreach (...) { ... } |
For example, inside the walkthrough's Blade form:
<label for="title">Title</label>
<input id="title" name="Title" value="{{ Old('Title', Model.Title) }}" />
<p role="alert">{{ Error('Title') }}</p>Run dotnet build to compile templates, then submit an invalid form and inspect the rendered page. A successful build alone cannot prove that a Razor-style helper accidentally pasted into Blade was evaluated: unknown @... text may remain literal. Verify the final HTML contains real URLs and __RequestVerificationToken, not helper source text.
Introduction
Blade views are files ending in .blade.html in resources/views. They use Blade's syntax: {{ }} echoes, @if … @endif, @foreach, @extends, @section, @yield, @push, and the other directives. The expressions inside are C#, not PHP: {{ Model.Title }} instead of {{ $post->title }}, and @foreach (var post in Model.Posts) instead of @foreach ($posts as $post).
{{-- resources/views/post/Show.blade.html --}}
@model Post
@extends('layouts.app')
@section('title', Model.Title)
@section('content')
<h1 class="text-2xl font-bold">{{ Model.Title }}</h1>
<p class="text-sm text-gray-500">by {{ Model.User?.Name }}</p>
@can('update', Model)
<a href="{{ Route('posts.edit', new { post = Model.Id }) }}">Edit</a>
@endcan
@endsectionA controller returns a Blade view exactly like any other view: return View(post); renders resources/views/post/Show.blade.html. The view locations, view helpers (Route, Old, Error, Can, ...), facades (Auth, Config, Lang, ...), components, and live components all work in Blade views.
Strings may use single quotes, as in Laravel: 'layouts.app' and Route('posts.index') become C# strings. A single character in single quotes ('a', '\n') stays a C# char.
How Blade Views Are Compiled
Blade views are compiled with your application, like Razor views. When you build, DotBlaze translates each .blade.html file into Razor and writes it under obj/ (for example obj/Debug/net10.0/blade/resources/views/post/Show.cshtml). Razor then compiles it into the application. So:
- A mistake in an expression is a compile error, not a runtime error. The translation keeps line numbers, so line 12 of the generated file is line 12 of your
.blade.htmlfile. - A Blade syntax mistake, such as an
@ifwithout@endif, fails the build with errorBLADE001and the file and line. - Rendering a Blade view is as fast as rendering a Razor view.
- After changing a view, rebuild, or use
dotblaze serve --watch(dotnet watch --no-hot-reload run). This rebuilds/restarts the app so the Blade MSBuild task runs for every edit. Plain managed hot reload can detect.blade.htmlchanges but report "No managed code changes to apply" and leave the view stale. See Hot Reload.
The DotBlaze package adds this build step to every application that references it. To turn it off, set <DotBlazeBlade>false</DotBlazeBlade> in the project file.
Blade and Razor Side by Side
One application can mix both kinds of views. post/Index.blade.html and auth/Login.cshtml can live in the same resources/views folder; View("Index") finds either. The dotblaze-app template, the sample app, and the views that dotblaze make:auth and dotblaze make:live create are all Blade; only _ViewImports.cshtml and _ViewStart.cshtml stay Razor files, because they configure Razor itself.
A view must be one or the other: having both Show.blade.html and Show.cshtml in the same folder is a build error (BLADE002).
Blade views need _ViewImports.cshtml to declare @inherits DotBlaze.DotBlazePage<TModel>, as the template's does. Their @model, @using, and @inject lines are Razor's directives and work unchanged.
Editor Support
In VS Code, install DotBlaze from the Visual Studio Marketplace (dotblaze.dotblaze-vscode), or run:
code --install-extension dotblaze.dotblaze-vscodeThe application template and sample app recommend this extension in .vscode/extensions.json and map .blade.html to DotBlaze Blade in .vscode/settings.json:
{
"files.associations": { "*.blade.html": "dotblaze-blade" },
"emmet.includeLanguages": { "dotblaze-blade": "html" },
"tailwindCSS.includeLanguages": { "dotblaze-blade": "html" },
"[dotblaze-blade]": { "editor.formatOnSave": false }
}For existing applications, replace the previous PHP Blade extension recommendation and blade language mappings with the values above. HTML, directives and expressions are highlighted as HTML/C# rather than PHP. Emmet uses HTML; install the separately recommended Tailwind CSS IntelliSense extension for class completion in a configured Tailwind project. See the Marketplace page for the current feature list and C# tooling requirements.
Formatting on save remains disabled until a safe mixed HTML/C#/Blade formatter is available; PHP Blade formatters can rewrite C# expressions incorrectly.
In JetBrains Rider, add *.blade.html to the Blade file type (Settings → Editor → File Types) if the Blade plugin is installed, or to HTML otherwise.
Displaying Data
Echo any C# expression with double braces. The output is HTML-encoded:
<p>Hello, {{ Model.Name }}.</p>
<p>The time is {{ DateTime.Now.ToString("HH:mm") }}.</p>
<p>{{ await Live.Render<PostSearch>() }}</p>Values that are already HTML, such as IHtmlContent returned by a helper, are written as they are.
Unescaped Data
{!! !!} writes the value without encoding. Only use it for HTML you trust:
<div>{!! Model.RenderedMarkdown !!}</div>Blade and JavaScript Frameworks
Prefix an echo with @ to leave it for a JavaScript framework, and wrap a larger block in @verbatim:
<h1>Laravel</h1>
Hello, @{{ name }}.
@verbatim
<div class="container">Hello, {{ name }}.</div>
@endverbatim@@if prints @if. An @ that is not a Blade directive is left alone, so Alpine's shorthand (@click="open = true") and email addresses (ada@example.com) need no escaping. As in Laravel, an @ directly after a letter or digit is never a directive.
@json(value) writes a value as JSON, safe inside a <script> tag:
<script>
const tags = @json(Model.Tags);
</script>Blade Directives
If Statements
@if (Model.Posts.Count == 1)
One post.
@elseif (Model.Posts.Count > 1)
Many posts.
@else
No posts yet.
@endif
@unless (Auth.Check())
You are not signed in.
@endunless
@isset(Model.CoverPath)
<img src="{{ Storage.Disk('public').Url(Model.CoverPath) }}" alt="" />
@endisset
@empty(Model.Tags)
No tags.
@endempty@isset(x) is true when x is not null. @empty(x) is true for null, an empty string, false, and an empty collection.
Authentication, authorization, and environment checks:
@auth
Signed in as {{ Auth.User<User>()!.Name }}.
@else
<a href="{{ Route('login') }}">Log in</a>
@endauth
@guest
Welcome, guest.
@endguest
@can('update', Model)
<a href="...">Edit</a>
@elsecan('view', Model)
Read only.
@endcan
@cannot('delete', Model)
You can't delete this post.
@endcannot
@env('local', 'Staging')
Not in production.
@endenv
@production
<script src="/analytics.js"></script>
@endproduction@can and @cannot use the Gate. @env compares names with the ASP.NET Core environment (Development, Production, ...), ignoring case; local also matches Development.
Switch Statements
@switch (Model.Status)
@case("draft")
Draft
@break
@case("published")
Published
@break
@default
Unknown
@endswitchOnly @case and @default may appear directly inside @switch. C# does not let one case fall through into the next, so a case without @break simply ends at the next @case.
Loops
@for (var i = 0; i < 10; i++)
The current value is {{ i }}
@endfor
@foreach (var user in Model.Users)
<p>This is user {{ user.Id }}</p>
@endforeach
@forelse (var user in Model.Users)
<li>{{ user.Name }}</li>
@empty
<p>No users</p>
@endforelse
@while (queue.Count > 0)
<p>{{ queue.Dequeue() }}</p>
@endwhile@foreach uses C# syntax: var user in users, not $users as $user. A null list is treated as empty.
Skip an iteration or end the loop with @continue and @break, optionally with a condition:
@foreach (var user in Model.Users)
@continue(user.Type == 1)
<li>{{ user.Name }}</li>
@break(user.Number == 5)
@endforeachThe Loop Variable
Inside @foreach and @forelse, Loop describes the current iteration, like Blade's $loop:
@foreach (var user in Model.Users)
@if (Loop.First)
This is the first iteration.
@endif
{{ Loop.Iteration }} of {{ Loop.Count }}: {{ user.Name }}
@endforeach| Property | Description |
|---|---|
Loop.Index | The index of the current iteration (starts at 0). |
Loop.Iteration | The current iteration (starts at 1). |
Loop.Remaining | The iterations remaining in the loop. |
Loop.Count | The total number of items. |
Loop.First | Whether this is the first iteration. |
Loop.Last | Whether this is the last iteration. |
Loop.Even | Whether this is an even iteration. |
Loop.Odd | Whether this is an odd iteration. |
Loop.Depth | The nesting level of the current loop (starts at 1). |
Loop.Parent | In a nested loop, the parent's loop variable. |
Conditional Classes and Attributes
@class builds a class attribute from strings and (name, condition) pairs; @style does the same for inline styles:
<span @class("p-4", ("font-bold", isActive), ("text-gray-500", !isActive), ("bg-red", hasError))></span>
<span @style("background-color: red", ("font-weight: bold", isActive))></span><span class="p-4 font-bold"></span>
<span style="background-color: red; font-weight: bold;"></span>A Dictionary<string, bool> works too. @checked, @selected, @disabled, @readonly, and @required write the attribute when the condition is true and leave it out when it is false:
<input type="checkbox" name="active" value="active" @checked(Old("active", user.Active) == "True") />
<select name="version">
@foreach (var version in Model.Versions)
<option value="{{ version }}" @selected(Old("version") == version)>{{ version }}</option>
@endforeach
</select>
<button type="submit" @disabled(Model.IsReadOnly)>Submit</button>NOTE
As in Razor views with DotBlaze's component tag helper, void elements (<input>, <img>, <br>) must be self-closing (<input ... />), and C# cannot be written directly inside a tag: use an attribute value (disabled="{{ x }}") or one of the directives above.
Including Subviews
@include renders another view. Dots in the name are folders, so @include('shared.errors') renders resources/views/shared/errors:
<div>
@include('shared.errors')
<form>
<!-- Form Contents -->
</form>
</div>An included view gets the current view's model. Pass a second argument to give it another model:
@include('_Field', ("Email", "Email", "email", (string?)null))@includeIf('view.name', model) {{-- only if the view exists --}}
@includeWhen(isActive, 'view.name', model)
@includeUnless(isGuest, 'view.name', model)The @once Directive
@once renders its content only the first time it is reached during a request. This is useful in a component or partial that appears many times but needs a script only once:
@once
@push('scripts')
<script src="/chart.js"></script>
@endpush
@endonceRaw C#
@csharp runs C# statements:
@csharp
var total = Model.Items.Sum(i => i.Price);
@endcsharp
@csharp(var counter = 1)Blade's @php … @endphp still works as another name for the same directive, so views written with Laravel habits compile unchanged.
Comments
Blade comments are not included in the HTML sent to the browser:
{{-- This comment will not be present in the rendered HTML --}}Forms
<form method="POST" action="{{ Route('posts.update', new { post = Model.Id }) }}">
@csrf
@method('PUT')
<input name="title" value="{{ Old('title', Model.Title) }}" />
@error('title')
<span class="text-red-600">{{ message }}</span>
@enderror
</form>@csrf and @method render the CSRF token and method spoofing fields. @error renders its content when the field has a validation error; message holds the first message. @lang('Posts') and @choice('messages.apples', count) translate, like __() and TransChoice().
Components
Components (<x-alert>, <x-card>, named slots) and live component tags (<live:counter />) work in Blade views. Pass dynamic values with {{ }}:
<x-alert type="{{ hasError ? "error" : "success" }}" dismissible>{{ message }}</x-alert>A component's own view can be a Blade view too: its model is a Component.
{{-- resources/views/components/alert.blade.html --}}
@model Component
<div attributes="{{ Model.Attributes.Merge(new { @class = "rounded p-3", role = "alert" }) }}">
{{ Model.Slot }}
</div>Layouts Using Template Inheritance
Defining a Layout
A layout defines the page shell and uses @yield to show sections from the child view:
{{-- resources/views/layouts/app.blade.html --}}
<html>
<head>
<title>@yield('title', 'My App')</title>
</head>
<body>
@section('sidebar')
This is the master sidebar.
@show
<div class="container">
@yield('content')
</div>
@stack('scripts')
</body>
</html>@yield('title', 'My App') shows the child's title section, or the default. A section that ends with @show has default content in the layout; a child that defines the same section replaces it.
Extending a Layout
{{-- resources/views/child.blade.html --}}
@extends('layouts.app')
@section('title', 'Page Title')
@section('sidebar')
<p>This is my sidebar.</p>
@endsection
@section('content')
<p>This is my body content.</p>
@endsection@extends('layouts.app') uses resources/views/layouts/app, which may be a Blade or a Razor layout. As in Laravel:
- A Blade view without
@extendshas no layout, even though_ViewStart.cshtmlsets one for Razor views. - A Blade layout ignores content outside sections and sections it does not yield.
Mixing the two kinds:
- A Razor view with a Blade layout: the layout's
@yield('content')shows the Razor view's body (it has nocontentsection). The template's Razor pages, such as thosedotblaze make:authcreates, use the Blade layout this way. - A Blade view with a Razor layout: the Razor layout's
@RenderBody()shows the Blade view's content outside sections, and@RenderSection("name")shows its sections. Razor requires such a layout to render every section the view defines.
@endsection can also be written @stop. @parent (appending to the layout's section content) is not supported.
Stacks
Push content from a view, partial, or component to a named stack, and render the stack in the layout:
@push('scripts')
<script src="/example.js"></script>
@endpush
@prepend('scripts')
<script src="/first.js"></script>
@endprepend<head>
@stack('scripts')
</head>@prepend puts its content before what was pushed. Child views render before their layout, so their pushes appear in the layout's stacks. Content pushed after @stack has rendered (for example from the layout itself, below the stack) does not appear.
Directive Reference
| Blade | Generated Razor |
|---|---|
{{ expr }} / {!! expr !!} | @(expr) / @(Blade.Raw(expr)) |
@if (c) … @elseif (c) … @else … @endif | @if (c) { … } else if (c) { … } else { … } |
@unless (c), @isset(x), @empty(x) | @if (!(c)), @if ((x) is not null), @if (Blade.IsEmpty(x)) |
@auth, @guest, @can(...), @cannot(...), @env(...), @production | @if (Auth.Check()), @if (await Can(...)), ... |
@foreach (var x in items), @forelse … @empty | @foreach (var x in Blade.Each(items)) (keeps Loop up to date) |
@for (...), @while (...), @break, @continue | the same C# statements |
@switch (x), @case(v), @default, @break | switch (x) { case v: … break; } |
@extends('layouts.app') | Layout = "layouts/app" |
@section('name') … @endsection, @section('name', value) | @section name { … } |
@yield('name', default), @section … @show | Blade.Yield(...) |
@include('view', model) | await Html.PartialAsync("view", model) |
@push, @prepend, @stack, @once | DotBlaze's stack and once helpers |
@csrf, @method('PUT') | Csrf(), Method("PUT") |
@json(x), @class(...), @style(...), @checked(c), ... | DotBlaze helpers |
@lang('key'), @choice('key', n) | __("key"), TransChoice("key", n) |
@csharp … @endcsharp, @csharp(stmt) (or Blade's @php) | @{ … } |
@verbatim … @endverbatim, @{{ x }}, @@ | literal text |
{{-- comment --}} | removed |
@model, @using, @inject, @inherits | unchanged (Razor directives) |
To see exactly what a view compiles to, open its generated file under obj/<configuration>/<framework>/blade/.
Rendering Templates From Strings
Blade views are compiled with the application. For templates that live elsewhere and change at runtime, such as email templates that administrators edit in a database table, use BladeTemplate:
var template = BladeTemplate.Compile(row.Body); // parse (cached by content); throws on a syntax error
string html = template.Render(new { user, order }); // HTML: {{ }} output is encoded
string text = template.RenderText(new { user, order }); // plain text: nothing is encoded (subjects, text emails)For mail, new MailMessage().Template(body, data, subject: ...) does both; see templates from the database.
String templates run in a sandbox. Unlike a Blade view, whose expressions are C#, a string template can only read the data you pass it: no method calls, no new, no types, no @csharp. So it is safe to let users write them; the worst a template can do is show data you gave it, or fail. Within that data:
- Properties marked
[Hidden](such as a model's password) cannot be read. - Values such as
Type,Assembly, delegates,Task,Stream, andIServiceProvidercannot be reached.
The Template Language
<p>Hi {{ user.Name }},</p>
@if (order.Status == 'Paid')
<p>Thanks! We received {{ order.Total | number(2) }}.</p>
@elseif (order.DueAt != null)
<p>Please pay before {{ order.DueAt | date('d MMMM yyyy') }}.</p>
@endif
@forelse (var line in order.Lines)
<p>{{ Loop.Iteration }}. {{ line.Product }} × {{ line.Quantity }}</p>
@empty
<p>No items.</p>
@endforelse| Syntax | Notes |
|---|---|
{{ expr }}, {!! expr !!} | Echo (encoded in Render, never in RenderText), unescaped echo. |
@if, @elseif, @else, @unless, @isset(x), @empty(x) | A condition is false for null, false, 0, "", and an empty list. |
@foreach (var item in items), @forelse … @empty | With Loop (see the loop variable); var is optional. |
@break, @continue, @break(condition) | Inside loops. |
{{-- comment --}}, @{{ x }}, @@, @verbatim | As in Blade views. |
Expressions:
- Data: names from the data object (
user,order). The data can be an object (an anonymous object, a model), a dictionary, or aJsonElement(for data stored as JSON). - Access: members (
order.Customer.Name,order?.Customer) and indexes (lines[0],meta['key']). Names ignore case, souser.namefindsName. - Literals: strings in single or double quotes, numbers,
true,false,null. - Operators:
== != < > <= >=,+ - * / %(+also joins text),&&/and,||/or,!/not,??, andcondition ? a : b. - Enums: an enum compares with its name, so
order.Status == 'Paid'works.
Like in Blade, a directive alone on its line leaves no blank line behind, so plain-text templates come out clean.
Filters
Format a value with | and a filter, optionally with arguments; filters chain from left to right:
{{ user.Name | upper }}
{{ post.Body | limit(100) }}
{{ order.PlacedAt | date('dd/MM/yyyy') }}
{{ order.Notes | default('-') | nl2br }}
@if ((order.Lines | count) > 3) ... @endif| Filter | Result |
|---|---|
upper, lower, title, trim | Changes the text. |
limit(n, end = '...') | The first n characters, then end. |
default(value) | value when the input is null or empty. |
number(decimals = 0) | A number with thousands separators, in the current culture. |
date(format = 'd') | A date in a .NET format, in the current culture. |
count | The number of items (or characters). |
join(separator = ', ') | The items as text. |
nl2br | Encodes the text and turns line breaks into <br>. |
Register your own filters once, at startup (a service provider's Boot is a good place):
BladeTemplate.Filter("money", (value, args) => $"Rp {value:N0}");{{ order.Total | money }}A filter that returns IHtmlContent (such as new HtmlString(...)) is written without encoding.
Errors
Both compiling and rendering throw BladeTemplateException. Its Line and Column point into the template, and Reason describes the problem:
try
{
BladeTemplate.Compile(input.Body); // validate before saving
}
catch (BladeTemplateException e)
{
return Back().WithErrors(new { body = $"Line {e.Line}: {e.Reason}" });
}Compiling catches syntax errors. Rendering catches mistakes that depend on the data: an unknown variable or property (a typo such as user.Nmae), a filter that does not exist, or a @foreach over something that is not a list. A property of null is null rather than an error, so {{ order.Coupon.Code }} is empty when there is no coupon.
Differences From Laravel
- Expressions are C#:
Model.Title, not$post->title;@foreach (var p in posts), not@foreach ($posts as $p). The view's data is its model (@model Post), not an array of variables. @includepasses a model, not an array that is merged with the parent's variables.- Raw code blocks are
@csharp…@endcsharp; Blade's@php…@endphpis accepted as another name. @authand@guestdo not take a guard name, and@parent,@each,@aware,@props,@pushOnce,@hasSection,@sectionMissing,@dd, and@dumpare not available.@injectis Razor's form:@inject IMetrics Metrics.- Views are compiled at build time instead of on first use, so syntax errors surface when you build.
- Custom directives (
Blade::directive) are not supported. Write a helper method or a component instead. Blade::render($string, $data)runs PHP; DotBlaze'sBladeTemplateruns a sandboxed subset instead, so templates from users are safe.