Web开发面临的挑战之一是我们必须协调三种不同的客户端技术:HTML,CSS和Javascript。更糟糕的是,我们必须将这些组件放在页面上的不同位置:头部中的样式标记中的CSS,结束体标记之前的脚本标记中的Javascript以及正文中的HTML。如果您想将CSS和Javascript放在单独的文件中,请不要介意! 在实践中,这在构建单个页面时非常好用,因为我们可以分离我们的结构(HTML),样式(CSS)和逻辑(Javascript)。但是当我们想要构建可以轻松编写的模块化代码时,分别协调所有三个部分可能会很头疼。小工具是Yesod解决问题的方法。它们还有助于解决包含库(例如jQuery)的问题。 我们的四种模板语言--Hamlet,Cassius,Lucius和Julius--提供了构建输出的原始工具。小部件提供了粘合剂,使它们可以无缝地协同工作。
梗概
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
import Yesod
data App = App
mkYesod "App" [parseRoutes|
/ HomeR GET
|]
instance Yesod App
getHomeR = defaultLayout $ do
setTitle "My Page Title"
toWidget [lucius| h1 { color: green; } |]
addScriptRemote "https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"
toWidget
[julius|
$(function() {
$("h1").click(function(){
alert("You clicked on the heading!");
});
});
|]
toWidgetHead
[hamlet|
<meta name=keywords content="some sample keywords">
|]
toWidget
[hamlet|
<h1>Here's one way of including content
|]
[whamlet|<h2>Here's another |]
toWidgetBody
[julius|
alert("This is included in the body itself");
|]
main = warp 3000 App
复制代码
这会产生以下HTML(添加缩进):
<!DOCTYPE html>
<html>
<head>
<title>My Page Title</title>
<meta name="keywords" content="some sample keywords">
<style>h1{color:green}</style>
</head>
<body>
<h1>Here's one way of including content</h1>
<h2>Here's another</h2>
<script>
alert("This is included in the body itself");
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js">
</script><script>
$(function() {
$('h1').click(function() {
alert("You clicked on the heading!");
});
});
</script>
</body>
</html>
复制代码
小工具中有什么?
在一个非常肤浅的层面上,HTML文档只是一堆嵌套标签。这是大多数HTML生成工具采用的方法:您定义标记的层次结构并使用它完成。但我们想象一下,我想编写一个页面组件来显示导航栏。我希望这是“即插即用”:我在正确的时间调用该函数,并将导航栏插入层次结构中的正确位置。 这是我们肤浅的HTML生成崩溃的地方。除了HTML之外,我们的导航栏可能还包含一些CSS和JavaScript。当我们调用navbar函数时,我们已经渲染了标记,因此为CSS声明添加新的