英文:
How to add a class to the body tag in a Leaf base template
问题
我正在使用Vapor构建网站,并使用Leaf模板引擎。假设我在Base.leaf
中定义了以下基本模板:
<!DOCTYPE html>
<html lang="en">
<head>
<title>#(title)</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KK94CHFLLe+nY2dmCWGMq91rCGa5gtU4mk92HdvYe+M/SXH301p5ILy+dN9+nJOZ" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">
</head>
<body>
#import("content")
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ENjdO4Dr2bkBIFxQpeoTz1HIcje39Wm4jDKdf19U8gI4ddQ3GYNS7NTKfAdVQSZe" crossorigin="anonymous"></script>
</body>
</html>
在某些页面上,我希望有不同的背景颜色,所以我需要将bg-body-secondary
Bootstrap类应用到body
标签上。
对于扩展基本模板的页面,应用不同的类的推荐方法是什么?是否应该在传递给渲染页面的上下文中包含任何body
类(<body class="#(bodyClasses)">
)?将<body>
从基本模板中移到每个页面,以便可以在那里添加类?还有其他我可能忽略的方法吗?
感谢任何指导!
英文:
I'm building a site with Vapor and using the Leaf templating engine. Say I have the following base template defined in Base.leaf
:
<!DOCTYPE html>
<html lang="en">
<head>
<title>#(title)</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KK94CHFLLe+nY2dmCWGMq91rCGa5gtU4mk92HdvYe+M/SXH301p5ILy+dN9+nJOZ" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">
</head>
<body>
#import("content")
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ENjdO4Dr2bkBIFxQpeoTz1HIcje39Wm4jDKdf19U8gI4ddQ3GYNS7NTKfAdVQSZe" crossorigin="anonymous"></script>
</body>
</html>
On some pages, I want a different background color, so I need to apply the bg-body-secondary
bootstrap class to the body tag.
What is the recommended approach for applying different classes to the body tag for pages that extend the base template? Include any body classes in the context passed to render the page (<body class="#(bodyClasses)>
)? Move the <body>
out of the base into each page so classes can be added there? Something else I'm missing?
Thanks for any pointers!
答案1
得分: 1
最简单的方法是在渲染视图时将类作为上下文值传递。
return req.view.render("view",["class": "class1"])
然后在你的leaf模板中:
<div class="class1">
英文:
The easiest way is to pass the class as a context value when you render the view.
return req.view.render(“view”,[“class”: “class1”])
Then in you leaf:
<div class=“#(class)”>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论