Golang中如何将Buffalo的HTML标签从Bootstrap转换为Materialize

Golang中如何将Buffalo的HTML标签从Bootstrap转换为Materialize 有没有人之前做过这件事?我正在尝试在Buffalo框架中创建一个表单。看起来一切工作正常,但我无法将标签的默认布局从Bootstrap切换到Materialize。

我不确定要更改哪个参数以及如何更改它。我通过更改渲染函数成功移除了标签的Bootstrap布局,但随后我又不知道如何插入类和标签并将其更改为Materialize。

请帮我解决这个问题。如果你有任何解释这个问题的链接,请分享给我。我愿意接受任何建议。

1 回复

更多关于Golang中如何将Buffalo的HTML标签从Bootstrap转换为Materialize的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


在Buffalo框架中,将表单标签从Bootstrap切换到Materialize需要自定义表单渲染器。以下是具体实现方法:

首先创建自定义的Materialize表单渲染器:

package renderers

import (
    "github.com/gobuffalo/tags"
    "github.com/gobuffalo/tags/form"
)

type MaterializeForm struct {
    *form.Form
}

func (mf MaterializeForm) InputTag(field string, opts tags.Options) *tags.Tag {
    // 移除Bootstrap类并添加Materialize类
    if opts["class"] == nil {
        opts["class"] = ""
    }
    
    // 移除bootstrap相关类
    classStr := opts["class"].(string)
    // 可以添加逻辑移除bootstrap特定类名
    
    // 添加Materialize CSS类
    opts["class"] = classStr + " validate"
    
    input := mf.Form.InputTag(field, opts)
    
    // 为Materialize创建标签结构
    labelOpts := tags.Options{
        "body": field,
        "for":  opts["id"],
    }
    label := tags.New("label", labelOpts)
    
    // 创建包装容器
    divOpts := tags.Options{
        "class": "input-field",
    }
    div := tags.New("div", divOpts)
    div.Append(input)
    div.Append(label)
    
    return div
}

func NewMaterializeForm(opts tags.Options) *MaterializeForm {
    return &MaterializeForm{
        Form: form.New(opts),
    }
}

然后在你的Buffalo处理器中使用这个自定义渲染器:

func MyFormHandler(c buffalo.Context) error {
    // 创建自定义Materialize表单
    materializeForm := renderers.NewMaterializeForm(tags.Options{
        "action": "/submit",
        "method": "POST",
    })
    
    c.Set("form", materializeForm)
    return c.Render(200, r.HTML("form.html"))
}

在模板中这样使用:

<!-- form.html -->
<%= form.InputTag("Name", tags.Options{"label": "Your Name"}) %>
<%= form.InputTag("Email", tags.Options{"type": "email"}) %>
<%= form.SubmitTag("Submit") %>

对于更复杂的表单字段,你还需要重写其他方法:

func (mf MaterializeForm) SelectTag(field string, opts tags.Options) *tags.Tag {
    opts["class"] = "browser-default" // Materialize选择框类
    selectTag := mf.Form.SelectTag(field, opts)
    
    div := tags.New("div", tags.Options{"class": "input-field"})
    div.Append(selectTag)
    
    return div
}

func (mf MaterializeForm) CheckboxTag(field string, opts tags.Options) *tags.Tag {
    opts["class"] = "filled-in" // Materialize复选框类
    checkbox := mf.Form.CheckboxTag(field, opts)
    
    labelOpts := tags.Options{
        "body": opts["label"],
        "for":  opts["id"],
    }
    label := tags.New("label", labelOpts)
    label.Prepend(checkbox)
    
    return label
}

这种方法通过创建自定义表单渲染器来覆盖默认的Bootstrap样式,替换为Materialize CSS框架所需的HTML结构和类名。你需要根据Materialize的具体要求调整各个表单元素的包装结构和CSS类。

回到顶部