《Web Development with Go》中的html.template
模板应用,深入其它
main.go
package main
import (
//"encoding/json"
"fmt"
"log"
"net/http"
"strconv"
"time"
"html/template"
"github.com/gorilla/mux"
)
var templates map[string]*template.Template
func init() {
if templates == nil {
templates = make(map[string]*template.Template)
}
templates["index"] = template.Must(template.ParseFiles("templates/index.html", "templates/base.html"))
templates["add"] = template.Must(template.ParseFiles("templates/add.html", "templates/base.html"))
templates["edit"] = template.Must(template.ParseFiles("templates/edit.html", "templates/base.html"))
}
func renderTemplate(w http.ResponseWriter, name string, template string, viewModel interface{}) {
tmpl, ok := templates[name]
if !ok {
http.Error(w, "The template does not exist.", http.StatusInternalServerError)
}
err := tmpl.ExecuteTemplate(w, template, viewModel)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
type Note struct {
Title string `josn:"title"`
Description string `json: "description"`
CreatedOn time.Time `json:"createdon"`
}
type EditNote struct {
Note
Id string
}
var noteStore = make(map[string]Note)
var id int = 0
func getNotes(w http.ResponseWriter, r *http.Request) {
fmt.Println(noteStore)
renderTemplate(w, "index", "base", noteStore)
}
func addNote(w http.ResponseWriter, r *http.Request) {
renderTemplate(w, "add", "base", nil)
}
func saveNote(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
title := r.PostFormValue("title")
description := r.PostFormValue("description")
note := Note{title, description, time.Now()}
id++
k := strconv.Itoa(id)
noteStore[k] = note
http.Redirect(w, r, "/", 302)
}
func editNote(w http.ResponseWriter, r *http.Request) {
var viewModel EditNote
vars := mux.Vars(r)
k := vars["id"]
if note, ok := noteStore[k]; ok {
viewModel = EditNote{note, k}
} else {
http.Error(w, "Could not find the resource to edit.", http.StatusBadRequest)
}
renderTemplate(w, "edit", "base", viewModel)
}
func updateNote(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
k := vars["id"]
var noteToUpd Note
if note, ok := noteStore[k]; ok {
r.ParseForm()
noteToUpd.Title = r.PostFormValue("title")
noteToUpd.Description = r.PostFormValue("description")
noteToUpd.CreatedOn = note.CreatedOn
delete(noteStore, k)
noteStore[k] = noteToUpd
} else {
http.Error(w, "Could not find the resource to update.", http.StatusBadRequest)
}
http.Redirect(w, r, "/", 302)
}
func deleteNote(w http.ResponseWriter, r *http.Request) {
//Read value from route variable
vars := mux.Vars(r)
k := vars["id"]
// Remove from Store
if _, ok := noteStore[k]; ok {
//delete existing item
delete(noteStore, k)
} else {
http.Error(w, "Could not find the resource to delete.", http.StatusBadRequest)
}
http.Redirect(w, r, "/", 302)
}
func main() {
r := mux.NewRouter().StrictSlash(false)
fs := http.FileServer(http.Dir("public"))
r.Handle("/public/", fs)
r.HandleFunc("/", getNotes)
r.HandleFunc("/notes/add", addNote)
r.HandleFunc("/notes/save", saveNote)
r.HandleFunc("/notes/edit/{id}", editNote)
r.HandleFunc("/notes/update/{id}", updateNote)
r.HandleFunc("/notes/delete/{id}", deleteNote)
server := &http.Server{
Addr: ":8080",
Handler: r,
}
log.Println("Listening...")
server.ListenAndServe()
}
base.html
{{define "base"}}
<html>
<head>{{template "head" .}}</head>
<body>{{template "body" .}}</body>
</html>
{{end}}
add.html
{{define "head"}}<title>Add Note</title>{{end}}
{{define "body"}}
<h1>Add Note</h1>
<form action="/notes/save" method="post">
<p>Title:<br> <input type="text" name="title"></p>
<p>Description:<br>
<textarea rows="4" cols="50" name="description"></textarea> </p>
<p><input type="submit" value="submit"/> </p>
</form>
{{end}}
index.html
{{define "head"}}<title>Index</title>{{end}}
{{define "body"}}
<h1>Notes List</h1>
<p>
<a href="/notes/add">Add Note</a>
</p>
<div>
<table border="1">
<tr>
<th>Title</th>
<th>Description</th>
<th>Created On</th>
<th>Action</th>
</tr>
{{range $key,$value := .}}
<tr>
<td>{{$value.Title}}</td>
<td>{{$value.Description}}</td>
<td>{{$value.CreatedOn}}</td>
<td>
<a href="/notes/edit/{{$key}}">Edit</a>|
<a href="/notes/delete/{{$key}}">Delete</a>
</td>
</tr>
{{end}}
</table>
</div>
{{end}}
edit.html
{{define "head"}}<title>Edit Note</title>{{end}}
{{define "body"}}
<h1>Edit Note</h1>
<form action="/notes/update/{{.Id}}" method="post">
<p>Title:<br> <input type="text" value="{{.Note.Title}}" name="title"></p>
<p> Description:<br> <textarea rows="4" cols="50" name="description">
{{.Note.Description}}</textarea> </p>
<p><input type="submit" value="submit"/></p>
</form>
{{end}}



《Web Development with Go》中的html.template的更多相关文章
- Web Development Terms
I've come across lots of terms while learning web development. I'm feeling myself overwhelmed. Here ...
- Web 建站技术中,HTML、HTML5、XHTML、CSS、SQL、JavaScript、PHP、ASP.NET、Web Services 是什么(转)
Web 建站技术中,HTML.HTML5.XHTML.CSS.SQL.JavaScript.PHP.ASP.NET.Web Services 是什么?修改 建站有很多技术,如 HTML.HTML5.X ...
- Reloading Java Classes 301: Classloaders in Web Development — Tomcat, GlassFish, OSGi, Tapestry 5 and so on Translation
The Original link : http://zeroturnaround.com/rebellabs/rjc301/ Copyright reserved by Rebel Inc In t ...
- 《Agile Web Development With Rails》读后感--rails基于web设计的best Practices
最近看完<Agile Web Development with Rails>一书,受益匪浅.书中先是用一个简单的web应用带你进入Rails的世界,然后在你大致熟悉之后,再带你了解Rail ...
- 【外文阅读】Web Development in 2020: What Coding Tools You Should Learn---Quincy Larson
原文链接:https://mail.qq.com/cgi-bin/readtemplate?t=safety&check=false&gourl=https%3A%2F%2Fwww.f ...
- Learning web development with MDN
Learning web development with MDN Server-side website programming Dynamic Websites – Server-side pro ...
- Beginners Guide To Web Development
Web Development Front End Development Back End Development
- (转) Web 建站技术中,HTML、HTML5、XHTML、CSS、SQL、JavaScript、PHP、ASP.NET、Web Services 是什么?
Web 建站技术中,HTML.HTML5.XHTML.CSS.SQL.JavaScript.PHP.ASP.NET.Web Services 是什么? 建站有很多技术,如 HTML.HTML5.XHT ...
- Asp.net mvc web api 在项目中的实际应用
Asp.net mvc web api 在项目中的实际应用 前言:以下只是记录本人在项目中的应用,而web api在数据传输方面有多种实现方式,具体可根据实际情况而定! 1:数据传输前的加密,以下用到 ...
- C# asp.net IIS 在web.config和IIS中设置Session过期时间
有时候在web.config设置sessionState 或者类文件里设置Session.Timeout,在IIS里访问时每次都是达不到时间就超时,原因是因为在IIS中设置了Session的超时时间, ...
随机推荐
- Eureka+SpringBoot2.X版本实现优雅停服
在客户端添加如下配置 pom依赖 actuator.jar包 <dependency> <groupId>org.springframework.cloud</group ...
- Android Studio出现Failed to open zip file问题的解决方法
直接在网上找到gradle-3.3-all.zip下载下来,不要解压缩,放在类似下面的目录中 C:\Users\Administrator\.gradle\wrapper\dists\gradle-3 ...
- code snippet:依赖属性propa的小技巧
很早之前就玩过VS里面的code snippet,相当方便. 今天在用prop自动属性代码时,无意中用了一下propa,然后就自动出来了依赖属性的代码片段,太方便了,尤其是对于WPF新手来说,比如我这 ...
- WebSocket断开原因、心跳机制防止自动断开连接
1.断开原因 WebSocket断开的原因有很多,最好在WebSocket断开时,将错误打印出来. ws.onclose = function (e) { console.log('websocket ...
- JavaScript设计模式基础(二)
JavaScript 设计模式基础(一) 原型模式 在以类为中心的面向对象编程语言中,类和对象的关系就像铸模和铸件的关系,对象总是从类中创建.而原型编程中,类不是必须的,对象未必从类中创建而来,可以拷 ...
- python-基础-def(*agrs,**kwagrs)
1.*args,返回的数据类型为 tuple,使用方法如下图代码:**kwargs 返回的数据类型为 dict 使用方法如下图代码. def KeyWord_s(arg): print(arg,typ ...
- Java之DateFormat类
DateFormat类概述 java.text.DateFormat 是日期/时间格式化子类的抽象类,我们通过这个类可以帮我们完成日期和文本之间的转换,也就是可以在Date对象与String对象之间进 ...
- CF1062F Upgrading Cities
题意 由于这是个\(DAG\),我们考虑拓朴排序,求某个点能到的和能到它的点,这是两个问题,我们可以正反两边拓朴排序,这样就只用考虑它能到的点了 设\(f[x]\)表示\(x\)能到的点数\(+\)能 ...
- SpringBoot源码学习系列之@PropertySource不支持yaml读取原因
然后,为什么@PropertySource注解默认不支持?可以简单跟一下源码 @PropertySource源码: 根据注释,默认使用DefaultPropertySourceFactory类作为资源 ...
- adb devices无法连接mumu模拟器
解决方案: 如果你的android环境能够直接访问 adb 的相关指令.只需要把mumu模拟器打开 然后打开cmd -> 输入 adb connect 127.0.0.1:7555 就能直接连上 ...