dtll2016 2018-10-29 05:57
浏览 76

golang html模板格式不正确

this might be a very basic question as I am not familiar with web programming at all. I am trying to create a table using html template which content is filled through a go script. My problem is that the tag does not fall where I intended it to. This is the html used for the html template

<h1>Exchange Rate for {{.Title}}</h1>

<form action="/dateShow/react" method="POST">
<table>
    <tr>
        <td>From</td>
        <td>To</td>
        <td>Rate</td>
        <td>7-day avg</td>
    </tr>{{.Data}}
</table>
<div><input type="submit" value="Save"></div>
</form>

I was expecting that the GO script would print the "data" after the first "tr"tag and inside the "table" tag. Instead, this is what I get

<html><head></head><body><h1>Exchange Rate for 2018-07-02</h1>

<form action="/dateShow/react" method="POST">
&lt;tr&gt;&lt;td&gt;usd&lt;/td&gt;&lt;td&gt;idr&lt;/td&gt;&lt;td&gt;15.000000&lt;/td&gt;&lt;td&gt;14.238334&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;usd&lt;/td&gt;&lt;td&gt;sgd&lt;/td&gt;&lt;td&gt;1.320000&lt;/td&gt;&lt;td&gt;1.310000&lt;/td&gt;&lt;/tr&gt;
<table>
    <tbody><tr>
        <td>From</td>
        <td>To</td>
        <td>Rate</td>
        <td>7-day avg</td>
    </tr></tbody></table>
<div><input type="submit" value="Save"></div>
</form></body></html>

This is so weird to be as the "title" part works fine and landed Where I want it to. But not the case for the body

  • 写回答

1条回答 默认 最新

  • dougu5886 2018-10-29 13:40
    关注

    Just pass the entire slice of exchange rates to the template, and use range to iterate over it.

    For example, if you have a struct like:

    var ExchangeRates []ExchangeRate
    
    type ExchangeRate struct {
        From            string
        To              string
        Rate            float64
        SevenDayAverage float64
    }
    

    You will pass ExchangeRates to the template, and the template might look like:

    <table>
        <tbody><tr>
            <td>From</td>
            <td>To</td>
            <td>Rate</td>
            <td>7-day avg</td>
        </tr>
        {{range .ExchangeRates}}
        <tr>
            <td>{{.From}}</td>
            <td>{{.To}}</td>
            <td>{{.Rate}}</td>
            <td>{{.SevenDayAverage}}</td>
        </tr>
        {{end}}
        </tbody>
    </table>
    
    评论

报告相同问题?

悬赏问题

  • ¥20 易康econgnition精度验证
  • ¥15 线程问题判断多次进入
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致