[golang] call the struct function in the template range

here is the code of a struct

type Post struct {
    Id          int    `db:"id"`
    Title       string `db:"title"`
    Content     string `db:"content"`
    Create_time int64    `db:"create_time"`
}

func (p Post) AttrCreatetime() time.Time {
    return time.Unix(p.Create_time, 0)
}
 

How to call the function "AttrCreatetime" in the template range? 

That is very simple to achieve it. Here is the code of the html file.

                        {{range .posts}}
            <article class="article ar-in">
                <div class="ar">
                    <span class="ar-ti">
                        <a href="{{url "Post.View" .Id}}" title="{{.Title}}">{{.Title}}</a>
                    </span>
                    <small>{{.AttrCreatetime}}</small>
                </div>
                <div class="ar-ds">
                    {{.Content}}
                    <span class="ar-mr"><a href="{{url "Post.View" .Id}}">more...</a></span>
                </div>
            </article>
            {{end}}

See? {{.AttrCreatetime}} is now la!

 

Have fun with golang!

本文来自:博客园

感谢作者:davidhhuan

查看原文:[golang] call the struct function in the template range

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。