Razor 组件可以修改页面的 HTML <head>
元素内容,包括页标题<title>
元素、元数据<meta>
元素、<base>
和<link>
等。
HeadOutlet组件
在Blazor中,可以通过HeadOutlet
组件来控制HTML中的 <head>
内容。
HeadOutlet
组件用于<head>
元素内,用来渲染子组件中,PageTitle
和HeadContent
组件提供的内容。
例如在BlazorServer项目模板的App.razor
中,可以看到如下代码:
......
<head>......<HeadOutlet />
</head>
......
Blazor WebAssembly中的HeadOutlet
在客户端的项目(Blazor WebAssembly)应用中,HeadOutlet
组件在 Program
文件中被添加到客户端。
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
@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
......<head>......<HeadOutlet/><PageTitle>Page Title</PageTitle> </head>......