第三章 组件(8)- 控制 <head> 内容

Razor 组件可以修改页面的 HTML <head> 元素内容,包括页标题<title>元素、元数据<meta>元素、<base><link>等。

HeadOutlet组件

在Blazor中,可以通过HeadOutlet组件来控制HTML中的 <head> 内容。

HeadOutlet组件用于<head>元素内,用来渲染子组件中,PageTitleHeadContent组件提供的内容。

例如在BlazorServer项目模板的App.razor中,可以看到如下代码:

csharp 复制代码
......
<head>
    ......
    <HeadOutlet />
</head>
......

Blazor WebAssembly中的HeadOutlet

在客户端的项目(Blazor WebAssembly)应用中,HeadOutlet组件在 Program 文件中被添加到客户端。

csharp 复制代码
builder.RootComponents.Add<HeadOutlet>("head::after");

指定 ::after 伪选择器后,根组件的内容将追加到现有标头内容,而不是替换内容。 这使客户端项目可以在 wwwroot/index.html 中保留静态标头内容,而无需重复应用的 Razor 组件中的内容。

PageTitle和HeadContent组件

如果想要设置<title>元素,可以将<title>的内容,放置在Razor的 PageTitle 组件内,这样可以将其作为 HTML <title> 元素传递给 HeadOutlet 组件进行渲染。

如果想要设置<head>元素中除了<title>外的其他元素,可以将其放置在Razor的HeadContent组件中,其会将元素传递给HeadOutlet 组件进行渲染。

  • ControlHeadContent.razor

    csharp 复制代码
    @page "/control-head-content"
    
    <PageTitle>@title</PageTitle>
    
    <h1>Control <head> Content Example</h1>
    
    <p>
        Title: @title
    </p>
    
    <p>
        Description: @description
    </p>
    
    <HeadContent>
        <meta name="description" content="@description">
    </HeadContent>
    
    @code {
        private string description = "This description is set by the component.";
        private string title = "Control <head> Content";
    }

默认标题和布局标题

可以在App.razor或布局组件中使用PageTitle组件,如果同时在App.razor、布局组件和组件内部使用了PageTitle组件,那么其优先级为组件标题>布局标题>默认标题。

  • App.razor

    csharp 复制代码
    ......
    
    <head>
        ......
        <HeadOutlet/>
        <PageTitle>Page Title</PageTitle>
    </head>
    
    ......
相关推荐
用户69371750013843 小时前
Google 正在“收紧侧加载”:陌生 APK 安装或需等待 24 小时
android·前端
蓝帆傲亦3 小时前
Web 前端搜索文字高亮实现方法汇总
前端
用户69371750013843 小时前
Room 3.0:这次不是升级,是重来
android·前端·google
似水明俊德4 小时前
02-C#.Net-反射-面试题
开发语言·面试·职场和发展·c#·.net
漫随流水4 小时前
旅游推荐系统(view.py)
前端·数据库·python·旅游
踩着两条虫5 小时前
VTJ.PRO 核心架构全公开!从设计稿到代码,揭秘AI智能体如何“听懂人话”
前端·vue.js·ai编程
阿蒙Amon6 小时前
C#常用类库-详解SerialPort
开发语言·c#
jzlhll1236 小时前
kotlin Flow first() last()总结
开发语言·前端·kotlin
似水明俊德7 小时前
02-C#.Net-反射-学习笔记
开发语言·笔记·学习·c#·.net
蓝冰凌7 小时前
Vue 3 中 defineExpose 的行为【defineExpose暴露ref变量】详解:自动解包、响应性与实际使用
前端·javascript·vue.js