You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Haskell的Blaze中使用自定义HTML属性

在blaze-html中使用自定义HTML属性

要添加data-bs-toggle这类自定义属性,blaze-html提供了底层的attribute函数来直接构造任意属性,具体做法如下:

  • 确保导入Text.Blaze.Html模块(该模块包含attribute核心函数)
  • 使用attribute函数定义自定义属性,第一个参数传入属性名字符串,第二个参数传入属性值字符串

对应你需要实现的Bootstrap导航栏按钮,完整可运行的代码示例:

import Text.Blaze.Html
import Text.Blaze.Html.Renderer.Text
import Text.Blaze.Html5 qualified as H
import Text.Blaze.Html5.Attributes qualified as A

navbarToggler :: H.Html
navbarToggler =
  H.button
    H.! A.class_ "navbar-toggler"
    H.! A.type_ "button"
    H.! attribute "data-bs-toggle" "collapse"
    H.! attribute "data-bs-target" "#navbarSupportedContent"
    H.! attribute "aria-controls" "navbarSupportedContent"
    H.! attribute "aria-expanded" "false"
    H.! attribute "aria-label" "Toggle navigation"
    $ H.span H.! A.class_ "navbar-toggler-icon"

补充说明:如果只是需要普通的data-*属性(如data-id),也可以使用dataAttribute函数,但对于data-bs-toggle这类带多段后缀的自定义属性,直接用attribute函数更简洁直接。

内容的提问来源于stack exchange,提问作者Adam D

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 22:29:53