Golang模板中如何解析HTML语法

Golang模板中如何解析HTML语法 大家好,我在Go模板中查看HTML格式时遇到了问题。 我有一个返回值的服务,我像这样在其中插入 <br>

func ToProduct(product ProductModel.Product) ProductResponse {
	return ProductResponse{
		Code:        product.Code,
		Title:       product.Title,
		Description: product.Description,
		Qty:         product.Qty,
		Price:       product.Price,
		Price1:      product.Price1,
		ShortNotes:  product.ShortNotes,
		Notes:       strings.Replace(product.Notes, ",", "<br>", -1),
		Image:       "/assets/img/products/" + product.Code + ".jpg",
		DivName:     product.DivName,
	}
}

在HTML模板中,我这样写:

<div>
    <div>
        <p>{{ .product.Notes }}</p>
    </div>
</div>

但是结果中的 <br> 显示为原始文本,而不是换行。


更多关于Golang模板中如何解析HTML语法的实战教程也可以访问 https://www.itying.com/category-94-b0.html

5 回复

只需记录变量的 JSON 输出

更多关于Golang模板中如何解析HTML语法的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


你能解释一下吗,抱歉我没太明白。

在你的包中添加日志记录,或者直接使用 fmt.Println 来输出你变量中的内容…

amansu:

在Go模板中查看HTML格式时遇到问题

Invalid JSON!
Error: Parse error on line 1:
ProductResponse{ C
^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[', got 'undefined'

在Go模板中,HTML内容默认会被转义。要解析HTML语法,需要使用template.HTML类型。以下是解决方案:

func ToProduct(product ProductModel.Product) ProductResponse {
    // 将替换后的字符串转换为template.HTML类型
    notes := template.HTML(strings.Replace(product.Notes, ",", "<br>", -1))
    
    return ProductResponse{
        Code:        product.Code,
        Title:       product.Title,
        Description: product.Description,
        Qty:         product.Qty,
        Price:       product.Price,
        Price1:      product.Price1,
        ShortNotes:  product.ShortNotes,
        Notes:       notes,  // 使用template.HTML类型
        Image:       "/assets/img/products/" + product.Code + ".jpg",
        DivName:     product.DivName,
    }
}

同时需要修改ProductResponse结构体中的Notes字段类型:

type ProductResponse struct {
    Code        string
    Title       string
    Description string
    Qty         int
    Price       float64
    Price1      float64
    ShortNotes  string
    Notes       template.HTML  // 修改为template.HTML类型
    Image       string
    DivName     string
}

模板代码保持不变:

<div>
    <div>
        <p>{{ .product.Notes }}</p>
    </div>
</div>

这样<br>标签就会被正确解析为HTML换行符。注意:使用template.HTML会绕过HTML转义,确保内容来源可信,避免XSS攻击。

回到顶部