User 69e88e27
发布于:2026-01-13
layout 标签用于设置模板使用的布局文件,或者禁用布局渲染。布局文件提供了页面的整体结构(如 HTML 骨架、导航栏、页脚等),模板内容会被插入到布局的指定位置。{% layout "布局名称" %} <!-- 使用指定布局 -->
{% layout none %} <!-- 不使用布局 -->
layout/ 目录下,例如:
- layout/theme.liquid - 默认主题布局
- layout/custom.liquid - 自定义布局
- layout/mobile.liquid - 移动端布局layout 标签,模板会默认使用 layout/theme.liquid 布局。<h1>页面标题</h1>
<p>页面内容</p>
{{ content_for_layout }} 位置。{% layout "custom" %}
<h1>页面标题</h1>
<p>页面内容</p>
layout/custom.liquid 作为布局文件。{% layout none %}
<html>
<head>
<title>独立页面</title>
</head>
<body>
<h1>完整 HTML 页面</h1>
</body>
</html>
{% if params.mobile == "true" %}
{% layout "mobile" %}
{% else %}
{% layout "desktop" %}
{% endif %}
<h1>页面标题</h1>
<p>页面内容</p>
{% response_type "json" %}
{% layout none %}
{
"status": "success",
"data": {}
}
{% response_type "turbo_stream" %}
{% layout none %}
<turbo-stream action="replace" target="content">
<template>
<div id="content">更新后的内容</div>
</template>
</turbo-stream>
content_for_layout 变量位置。layout/theme.liquid<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>{{ page.title }}</title>
{% meta_tags %}
</head>
<body>
<header>
<!-- 导航栏 -->
</header>
<main>
{{ content_for_layout }}
</main>
<footer>
<!-- 页脚 -->
</footer>
</body>
</html>
{% if params.device == "mobile" %}
{% layout "mobile" %}
{% elsif params.device == "tablet" %}
{% layout "tablet" %}
{% else %}
{% layout "desktop" %}
{% endif %}
<h1>响应式页面</h1>
{% response_type "json" %}
{% layout none %}
{
"articles": [
{% for article in articles %}
{
"id": {{ article.id }},
"title": {{ article.title | json }}
}{% unless forloop.last %},{% endunless %}
{% endfor %}
]
}
{% layout "error" %}
{% response_status 404 %}
<div class="error-page">
<h1>404 - 页面未找到</h1>
<p>抱歉,您访问的页面不存在。</p>
</div>
{% layout "print" %}
<h1>{{ page.title }}</h1>
<div class="content">
{{ page.body }}
</div>
content_for_layout 变量位置,而不是直接输出{% layout none %} 时,模板内容会直接输出,不会被任何布局包装,此时模板需要包含完整的 HTML 结构(如果返回 HTML 格式)turbo_stream、json、xml)时,必须禁用布局,避免布局的 HTML 结构影响响应格式response_type 或 response_status,布局中的设置会覆盖模板中的设置layout 标签放在模板的最前面,确保在渲染过程中正确设置布局layout/ 目录中,否则会使用默认布局或报错{%# ❌ 错误示例 %}
{% response_type "json" %}
<!-- 没有设置 layout none -->
{
"status": "success"
}
{%# ✅ 正确示例 %}
{% response_type "json" %}
{% layout none %}
{
"status": "success"
}
{%# ❌ 错误示例 %}
{% layout none %}
<h1>页面标题</h1>
<!-- 缺少完整的 HTML 结构 -->
{%# ✅ 正确示例 - 返回完整 HTML %}
{% layout none %}
<!DOCTYPE html>
<html>
<head>
<title>页面标题</title>
</head>
<body>
<h1>页面标题</h1>
</body>
</html>
{%# ✅ 正确示例 - 使用布局 %}
{% layout "theme" %}
<h1>页面标题</h1>
{%# ❌ 错误示例 %}
{% layout "nonexistent" %}
<h1>页面标题</h1>
layout/ 目录中,或使用存在的布局名称。response_type 返回非 HTML 格式时,始终配合 {% layout none %} 禁用布局layout 标签放在模板的最前面,与其他控制标签(如 response_type、response_status)一起layout 标签用于控制模板的布局渲染,可以指定使用特定的布局文件,或者禁用布局。当需要返回非 HTML 格式的响应时,必须禁用布局以避免 HTML 结构污染响应内容。正确使用此标签可以实现灵活的页面布局控制和响应格式管理。