第三章 组件(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>
    
    ......
相关推荐
杀死一只知更鸟debug10 分钟前
vue2,vue3,vue3 + vite 动态加载图片的方式
前端·javascript·vue.js
剪刀石头布啊25 分钟前
浏览器进程与事件循环
前端·浏览器
剪刀石头布啊26 分钟前
浏览器渲染原理
前端·浏览器
日记成书1 小时前
【HTML 基础教程】HTML 表格
前端·html
木木黄木木1 小时前
HTML5贪吃蛇游戏开发经验分享
前端·html·html5
画个逗号给明天"1 小时前
C#从入门到精通(4)
数据库·c#
无名之逆1 小时前
hyperlane:Rust HTTP 服务器开发的不二之选
服务器·开发语言·前端·后端·安全·http·rust
李鸿耀1 小时前
前端包管理工具演进史:从 npm 到 pnpm 的技术革新
前端·面试
麓殇⊙1 小时前
前端基础知识汇总
前端
MariaH1 小时前
邂逅jQuery库
前端