跳至正文

页面元数据 ​

简介 ​

用户在搜索结果中发现你的商品,或在聊天中分享链接时,标题、描述和预览图都来自文档的 <head>。搜索引擎爬虫和链接预览工具会在 JavaScript 执行前读取初始 HTML 响应,因此这些标签需要在服务器上渲染。laravel::head 可以在服务器上为视图和 Inertia 页面构建头部元数据。

用 Head 值描述元数据。应用设置全局默认值,路由可以追加静态元数据,处理器则在返回响应前合并请求专属的元数据。例如,这个处理器使用模型字段设置商品的标题和描述:

rust
use laravel::head::{self, Head};
use laravel::prelude::*;
use laravel::view::View;

use crate::models::Product;

pub async fn show(product: Product) -> laravel::Result<View> {
    head::merge(Head::new().title(&product.name).description(&product.summary));

    Ok(view("products.show", data! { product }))
}

渲染文档头部 ​

新应用已经在 Inertia 根视图中渲染了头部元数据。为服务端渲染的视图创建布局时,也请在布局中加入头部辅助函数。

在视图中渲染 ​

在布局的 <head> 内调用 head(),放在 charset 和 viewport 等静态标签之后:

html
<!-- resources/views/layouts/app.html -->

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    {{ head() }}
</head>

头部随视图一起渲染,请在处理器返回前调用 head::merge。在 {{ head() }} 之后用 vite(..) 加载样式表和脚本。

在 Inertia 页面中渲染 ​

Inertia 的根视图使用 {{ inertia_head }} 来渲染头部,普通视图则使用 head()。Laravel 还将页面标签放入 head prop,以便 Inertia 客户端在用户切换页面时更新文档头部。新应用已在 resources/js/app.tsx 中通过 serverHead 选项启用该功能:

ts
createInertiaApp({
    serverHead: true,
    // ...
});

请省略 Inertia 客户端的 title 回调,因为 Laravel 已在服务器上应用标题模板。使用 head::merge 设置标题、描述和社交标签,并将 Inertia 的 <Head> 组件留给服务端未渲染的标签。如果两边都设置 <title>,客户端会在水合后覆盖标题,而爬虫看到的仍是服务端的标题。

执行局部重载(例如 router.reload({ only: ['reviews'] }))时会省略 head prop,因此刷新其他 props 时页面会保留已有的头部标签。

设置默认值 ​

Laravel 默认在每个页面标题末尾追加应用名称,例如 About · Laravel。大多数应用还需要为所有页面设置默认描述、规范 URL 和社交标签。可以在 src/app.rs 的 with_head 中配置默认值:

rust
use laravel::head::{Head, OgType, TwitterCard};
use laravel::prelude::*;

Application::configure()
    .with_head(|head, config| {
        head.defaults(
            Head::new()
                .description("Build something great.")
                .canonical()
                .og_type(OgType::Website)
                .og_site_name(&config.app.name)
                .twitter_card(TwitterCard::SummaryLargeImage),
        );
    })

canonical() 会为去除查询字符串的当前 URL 输出 <link rel="canonical"> 标签,因此 /products?utm_source=news 和 /products 具有相同的规范 URL。若要保留分页等特定查询参数,请使用 canonical_with_query(["page"]);若要指定完全不同的 URL,请使用 canonical_url("/products/1")。

标题 ​

标题模板中的 %s 会被替换为页面标题。默认模板是 %s · {app name},因此 title("About") 会渲染为 About · Laravel。没有标题的页面仅显示应用名称;在全局默认值中设置的 title(...) 会原样渲染,跳过模板。

要在全局或某个路由组(例如管理后台)自定义模板,请调用 title_template。要让单个页面跳过模板,请使用 exact_title:

rust
Head::new().title_template("%s | Laravel News")

Head::new().exact_title("Laravel | The Rust Web Framework")

错误页面 ​

默认情况下,每个错误页面都使用 HTTP 状态的原因短语作为标题,例如 Not Found · Laravel。错误页面通常应避免被搜索引擎收录,404 页面也可以提供更清晰的描述。请在 with_head 中配置错误元数据,用 errors 指定所有错误页面的设置,用 error 针对特定状态码设置:

rust
use laravel::head::{Head, Robots};
use laravel::prelude::*;

Application::configure()
    .with_head(|head, _| {
        head.errors(Head::new().robots([Robots::NoIndex, Robots::Follow]));

        head.error(
            404,
            Head::new().description("The page you are looking for could not be found."),
        );
    })

错误元数据覆盖路由和处理器的元数据,适用于错误视图、Inertia 错误页面以及自定义渲染器。错误页默认省略规范链接,你可以通过错误元数据显式设置它。

路由元数据 ​

联系页面的标题、整个管理区的 robots 规则等元数据是静态的。你可以直接通过 with_head 将 Head 附加到路由、路由组或资源路由上:

rust
use laravel::head::{Head, Robots};
use laravel::prelude::*;

pub fn routes(route: &mut Router) {
    route
        .view("/contact", "contact")
        .with_head(Head::new().title("Contact Us").description("Get in touch."));

    route
        .with_head(Head::new().robots(Robots::None))
        .prefix("/admin")
        .group(|route| {
            route
                .get("/dashboard", admin::dashboard)
                .with_head(Head::new().title("Dashboard"));
        });
}

当多个嵌套组或路由设置同一标签时,Laravel 优先使用范围最具体的值。路由覆盖所属组,内层组覆盖外层组。

页面元数据 ​

多数元数据取决于当前请求,例如某个商品的名称和照片。请在渲染响应前,在处理器或中间件中调用 head::merge。一次请求可多次调用 head::merge,后续调用覆盖之前设置的值。

例如,这个处理器根据商品的 image_url 和 image_alt 列设置 Open Graph 图片,并让搜索引擎忽略未发布的草稿:

rust
use laravel::head::{self, Head, OgImage, OgType};
use laravel::prelude::*;
use laravel::view::View;

use crate::models::Product;

pub async fn show(product: Product) -> laravel::Result<View> {
    head::merge(
        Head::new()
            .title(&product.name)
            .og_type(OgType::Website)
            .og_image(
                OgImage::new(&product.image_url)
                    .alt(&product.image_alt)
                    .size(1200, 630),
            ),
    );

    if product.published_at.is_none() {
        head::merge(Head::new().hidden_from_robots());
    }

    Ok(view("products.show", data! { product }))
}

head::merge 可以接收任何实现了 Into<Head> 的值,因此你也可以在模型旁边实现 From<&Product> for Head,在处理器中直接传入模型引用:

rust
use laravel::head::Head;

impl From<&Product> for Head {
    fn from(product: &Product) -> Self {
        Head::new().title(&product.name).description(&product.summary)
    }
}
rust
pub async fn show(product: Product) -> laravel::Result<View> {
    head::merge(&product);

    Ok(view("products.show", data! { product }))
}

多层元数据如何合并 ​

Laravel 按优先级从低到高合并以下五层元数据:

  1. 应用名称,作为后备标题。
  2. 在 src/app.rs 中通过 head.defaults(...) 注册的全局默认值。
  3. 路由组上的元数据,然后是直接附加到路由上的元数据。
  4. 请求期间对 head::merge(...) 的各次调用,按调用顺序应用。
  5. 对于错误响应,先以 HTTP 状态的原因短语作为标题,再应用 head.errors(...) 和 head.error(status, ...)。

对于 title 或 description 等单值标签,高层的值优先,低层的其他标签仍然保留。例如,处理器只设置标题时,路由设置的描述仍然有效。备用语言等可重复的标签会合并;若高层重新定义同一条目,则使用高层的值。页面的 Open Graph 图片、视频或音频会替换全局默认值,这样商品照片就不会与站点的默认分享图一起出现。

Open Graph 和 Twitter ​

在社交媒体或聊天应用中分享链接时,预览工具会读取页面的 Open Graph 和 Twitter Card 标签。使用前面配置的全局默认值,在 /products/1 处理器中调用 head::merge:

rust
use laravel::head::{self, Head, OgImage};

head::merge(
    Head::new()
        .title("Trail Running Shoes")
        .description("Lightweight waterproof shoes built for mountain trails.")
        .og_image(OgImage::new("/images/shoes.jpg").alt("Trail Running Shoes")),
);

会在文档的 <head> 中生成以下标签:

html
<title>Trail Running Shoes · Laravel</title>
<meta name="description" content="Lightweight waterproof shoes built for mountain trails.">
<link rel="canonical" href="https://example.com/products/1">
<meta property="og:type" content="website">
<meta property="og:site_name" content="Laravel">
<meta property="og:title" content="Trail Running Shoes · Laravel">
<meta property="og:description" content="Lightweight waterproof shoes built for mountain trails.">
<meta property="og:image" content="https://example.com/images/shoes.jpg">
<meta property="og:image:alt" content="Trail Running Shoes">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="Trail Running Shoes · Laravel">
<meta name="twitter:description" content="Lightweight waterproof shoes built for mountain trails.">
<meta name="twitter:image" content="https://example.com/images/shoes.jpg">
<meta name="twitter:image:alt" content="Trail Running Shoes">

只要页面包含任何 Open Graph 标签,og:title 和 og:description 就会自动回退到页面标题和描述。同样,页面存在 Twitter 标签(例如默认卡片)时,Twitter 标签会回退到相应的 Open Graph 值。通过 og_title、og_description、twitter_title、twitter_description 或 twitter_image 显式设置的值始终优先。

社交平台的爬虫要求使用完整 URL,因此 /images/shoes.jpg 等相对图片路径会自动扩展为绝对 URL。

图标、资源提示和其他标签 ​

浏览器还会读取 <head> 获取站点图标、主题色、资源预加载提示和 RSS 或 Atom 订阅源。大多数应用只需在 with_head 的 head.defaults(...) 中统一配置:

rust
use laravel::head::{Feed, Head, Icon, ImageType, Link, Media, Preload};

head.defaults(
    Head::new()
        .theme_color("#ffffff")
        .theme_color_for(Media::Dark, "#111827")
        .icon(Icon::new("/favicon.svg").mime(ImageType::Svg))
        .apple_touch_icon(Icon::new("/apple-touch-icon.png").sizes("180x180"))
        .manifest("/site.webmanifest")
        .preconnect("https://fonts.bunny.net")
        .preload("/fonts/inter.woff2", Preload::Font)
        .alternate("fr", "https://example.com/fr/about")
        .feed(Feed::atom("/feed.atom").title("Laravel Atom"))
        .meta("format-detection", "telephone=no")
        .link(
            Link::new("search", "/opensearch.xml")
                .attr("type", "application/opensearchdescription+xml"),
        ),
);

对于没有专用辅助方法的标签,请使用最后两行所示的 meta 或 link。

在分页页面中,把分页器传给 paginated。它会在规范 URL 中保留分页器的页码参数(如 page 或 cursor),并在存在相邻页面时生成 <link rel="prev"> 和 <link rel="next"> 标签:

rust
use laravel::head::{self, Head};
use laravel::prelude::*;
use laravel::view::View;

use crate::models::Product;

pub async fn index() -> laravel::Result<View> {
    let products = Product::query().order_by(Product::id).paginate(15).await?;

    head::merge(Head::new().paginated(&products));

    Ok(view("products.index", data! { products }))
}

如果你手动生成分页链接,请直接设置 canonical_with_query(["page"])、prev_page 和 next_page。

结构化数据 ​

搜索引擎通过读取 JSON-LD 结构化数据展示富媒体搜索结果,例如在商品的搜索结果旁显示价格和库存状态。在 Head 上调用 schema 即可输出 JSON-LD 脚本。laravel::head::schema 模块为 Article、BlogPosting、Product、Offer、Brand、Breadcrumbs、Faq、Organization、Person、WebPage 和 WebSite 提供构建器:

rust
use laravel::head::schema::{Availability, Breadcrumbs, Offer, Product};
use laravel::head::{self, Head};

head::merge(
    Head::new()
        .schema(
            Product::new().name("Running shoes").offers(
                Offer::new()
                    .price(49.99)
                    .currency("USD")
                    .availability(Availability::InStock),
            ),
        )
        .schema(
            Breadcrumbs::new()
                .item("Home", "https://example.com")
                .item("Shop", "https://example.com/shop"),
        ),
);

对于其他 schema.org 类型,可以使用 Thing 动态构建,例如 Thing::new("Recipe").set("name", "Pancakes")。如果应用中的多个位置会复用自定义 schema 类型,可为 Serialize 结构体实现 Schema:

rust
use laravel::head::schema::Schema;

#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct JobPosting {
    title: String,
}

impl Schema for JobPosting {
    fn schema_type(&self) -> &str {
        "JobPosting"
    }
}

空字段请直接省略,避免传入空字符串或 None。调试模式下,包含空值的 schema 会渲染失败,并报告对应字段的路径;在生产环境中,Laravel 会记录警告并跳过该 schema。

测试头部元数据 ​

在 HTTP 测试中,对响应调用 assert_head(),即可用相同的断言检查 HTML 视图的 <head> 或 Inertia 页面的 head prop:

rust
use laravel::testing::prelude::*;

#[laravel::test]
async fn product_pages_have_social_tags(app: Application) {
    app.get("/products/1")
        .await
        .assert_head()
        .title("Trail Running Shoes · Laravel")
        .meta("og:title", "Trail Running Shoes · Laravel")
        .link("canonical", "http://localhost/products/1")
        .schema("Product")
        .missing("robots");
}
断言检查内容
title(text)头部恰好包含一个带指定文本的 <title>。
meta(name, content)具有指定 name 或 property 的 <meta> 标签包含预期内容。
link(rel, href)<link> 标签具有指定的 rel 和 URL。
schema(type)JSON-LD schema 具有指定的 @type,例如 Product。
has(key)、missing(key)匹配键的标签存在或缺失,例如 robots、og:title 或 canonical。

要验证局部重载省略了 head prop,请重载页面并断言 missing("head"):

rust
#[laravel::test]
async fn reviews_reload_without_the_head(app: Application) {
    app.get("/products/1")
        .await
        .assert_inertia()
        .reload_only(&["reviews"])
        .await
        .missing("head");
}