代码改变世界

Go Web开发之Revel - Hello World

2012-12-28 14:43  Danny.tian  阅读(3047)  评论(0编辑  收藏  举报

下面结合之前创建的myapp做一个提交表单的demo

首先编辑app/views/Application/Index.html 模板文件添加一下form表单

<form action="/Application/Hello" method="GET">
    <input type="text" name="myName" />
    <input type="submit" value="Say hello!" />
</form>

刷新表单

我们提交一下表单

报错:没有找到匹配的action,下面我们来添加一个

func (c Application) Hello(myName string) rev.Result {
    return c.Render(myName)
}

接着我们创建视图,路径为:app/views/Application/Hello.html ,内容如下:

{{set . "title" "Home"}}
{{template "header.html" .}}

<h1>Hello {{.myName}}</h1>
<a href="/">Back to form</a>

{{template "footer.html" .}}

在文本框中填入内容然后提交表单

最后我们添加一些验证,把文本框中的内容要求为必填并且最少三个字符,我们来编辑你的action app/controllers/app.go 文件

func (c Application) Hello(myName string) rev.Result {
    c.Validation.Required(myName).Message("Your name is required!")
    c.Validation.MinSize(myName, 3).Message("Your name is not long enough!")

    if c.Validation.HasErrors() {
        c.Validation.Keep()
        c.FlashParams()
        return c.Redirect(Application.Index)
    }

    return c.Render(myName)
}

修改app/views/Application/Index.html模板文件

<h1>Aloha World</h1>

{{range .errors}}
    <p style="color:#c00">
        {{.Message}}
    </p>
{{end}}

<form action="/Application/Hello" method="GET">
    <input type="text" name="myName" value="{{.flash.myName}}" />
    <input type="submit" value="Say hello!" />
</form>

现在回到Index页面,如果填写内容不符合要求将提示错误信息如下所示:

至此结束。