I have an if else block in my template. when else if is true it is rendered always empty as if else or else if is not there
here is my template
in this case, it renders nothing
And also I am using text/template because html/template send the page completely empty
//the template
<script>
{{if.PassChange}}
swal("{{.Lang.Success}}", "{{.Lang.PleaseLogin}}", "success")
{{end}}
{{if.UserExists}}
swal("{{.Lang.Fail}}", "{{.Lang.AlreadyMember}}", "error")
{{end}}
</script>
//rendering part
BasePath.Get("/", func(w http.ResponseWriter, r *http.Request) {
tpl.ExecResponse(w, struct{Lang map[string]string ; UserExists bool}{Lang:lang.GetLang(r),UserExists:true})
})
If you print the error from executing the template, you will find that the template cannot evaluate the field PassChange. One possible fix is to add a PassChange field to the struct.
tpl.ExecResponse(w, struct{PassChange bool; Lang map[string]string ; UserExists bool}{Lang:lang.GetLang(r),UserExists:true})
Related
I need to create an html page that display all the "forums" present in the database in my .html file.
Example:
<body>
{{with index . 0}}
{{.Name}}<br>{{.Descr}}</td>
{{end}}
{{with index . 1}}
{{.Name}}<br>{{.Descr}}
{{end}}
</body>
func index(w http.ResponseWriter, r *http.Request) {
forums := GetForumsFromDB() // return a slice of type Forum from the db
tpl.ExecuteTemplate(w, "index.html", forums)
}
type Forum struct {
Id int
Name string
Descr string
}
But in this case I need to already know how many forums are there in the db when writing the .html file. How should I approach this? Should I pass the html into the template together with my slice? Should I use a method of Forum that return the html for every forum?
Use range:
{{range .}}
{{.Name}}<br>{{.Descr}}
{{end}}
I have an html template where i want to insert some JavaScript code from outside of template itself. In my template data struct i have created a string field JS string and call it with {{.JS}}. The problem is that everything in browser is escaped:
newlines are \n
< and > are \u003c and \u003e
" is \"
Same symbols inside of a template are fine. If I Print my JS field into console it is also fine. I have seen some similar problems solved by using template.HTML type instead of string. In my case it does not work at all.
EDIT 1
The actual context is
<script language="JavaScript">
var options = {
{{.JS}}
};
</script>
Either change the field's type to template.JS like so:
type Tmpl struct {
// ...
JS template.JS
}
Or declare a simple function that converts a string to the template.JS type like so:
func toJS(s string) template.JS {
return template.JS(s)
}
And then register the function with the Funcs method and use it in your template like so:
{{toJS .JS}}
Try setting the type of JS to template.JS:
import "html/template"
type x struct {
JS template.JS
}
Documentation can be found here.
I know rendering a partial template with additional parameters is possible in Ruby, how can I do it in Go?
I have a partial template _partial1.tmpl:
<div>
text1
{{if foo}}
text2
{{end}}
</div>
using it from the parent template parent.tmpl:
<div>
{{ template "partial1", }} // how do I pass foo param here??
</div>
How do I pass the parameter foo to the partial?
The documentation states that the template directive has two forms:
{{template "name"}}
The template with the specified name is executed
with nil data.
{{template "name" pipeline}}
The template with the specified name is
executed with dot set to the value of the pipeline.
The latter accepts a pipeline statement which's value is then set to the dot value in the executed template. So calling
{{template "partial1" "string1"}}
will set {{.}} to "string1" in the partial1 template. So while there is no way to set the name foo in the partial, you can pass parameters and they will appear in .. Example:
template.html
<div>
{{ template "partial1.html" "muh"}} // how do I pass foo param here??
</div>
partial1.html
{{if eq . "muh"}}
blep
{{else}}
moep
{{end}}
main.go
import (
"html/template"
"fmt"
"os"
)
func main() {
t,err := template.ParseFiles("template.html", "partial1.html")
if err != nil { panic(err) }
fmt.Println(t.Execute(os.Stdout, nil))
}
Running this program will print the template's contents with blep from the partial. Changing the passed value will change this behaviour.
You can also assign variables, so assigning . to foo is possible in the partial:
{{ $foo := . }}
I'm trying to generate a web page in Go lang. I'm currently using the Goji framework ( http://goji.io ) and I want to generate all of the heads and parts of the body of the web-page, but then I want some of the content to be written based on results from the code.
For example as in PHP, one can write HTML, js, or CSS and then in the PHP tags, write the code which is interpreted there.
How can I write my html, css, and js and then have Golang code within it that is complied and executed as the page is rendered?
As mentioned in issue 13, use Go html/template package.
i.e.
// Shorthand
type M map[string]interface{}
func viewHandler(c web.C, w http.ResponseWriter, r *http.Request) {
title := c.URLParams["title"]
p, err := loadPage(title)
if err != nil {
...
}
// do other things
template.ExecuteTemplate(w, "results.html", M{
"title": title,
"results": results,
"pagination": true,
}
}
results.html
{{range .Results }}
<h1>{{ Result.Name }}</h1>
<p>{{ Result.Body }}</p>
{{ end }}
Using a template is also recommended in zenazn/goji/example/main.go.
elithrar also references in the comments the "Writing Web Applications article, section The html/template package" for more.
Before I being a bit of background, I am very new to go programming language. I am running go on Win 7, latest go package installer for windows. I'm not good at coding but I do like some challenge of learning a new language. I wanted to start learn Erlang but found go very interesting based on the GO I/O videos in youtube.
I'm having problem with capturing POST form values in GO. I spend three hours yesterday to get go to print a POST form value in the browser and failed miserably. I don't know what I'm doing wrong, can anyone point me to the right direction? I can easily do this in another language like C#, PHP, VB, ASP, Rails etc. I have search the entire interweb and haven't found a working sample. Below is my sample code.
Here is Index.html page
{{ define "title" }}Homepage{{ end }}
{{ define "content" }}
<h1>My Homepage</h1>
<p>Hello, and welcome to my homepage!</p>
<form method="POST" action="/">
<p> Enter your name : <input type="text" name="username"> </P>
<p> <button>Go</button>
</form>
<br /><br />
{{ end }}
Here is the base page
<!DOCTYPE html>
<html lang="en">
<head>
<title>{{ template "title" . }}</title>
</head>
<body>
<section id="contents">
{{ template "content" . }}
</section>
<footer id="footer">
My homepage 2012 copy
</footer>
</body>
</html>
now some go code
package main
import (
"fmt"
"http"
"strings"
"html/template"
)
var index = template.Must(template.ParseFiles(
"templates/_base.html",
"templates/index.html",
))
func GeneralHandler(w http.ResponseWriter, r *http.Request) {
index.Execute(w, nil)
if r.Method == "POST" {
a := r.FormValue("username")
fmt.Fprintf(w, "hi %s!",a); //<-- this variable does not rendered in the browser!!!
}
}
func helloHandler(w http.ResponseWriter, r *http.Request) {
remPartOfURL := r.URL.Path[len("/hello/"):]
fmt.Fprintf(w, "Hello %s!", remPartOfURL)
}
func main() {
http.HandleFunc("/", GeneralHandler)
http.HandleFunc("/hello/", helloHandler)
http.ListenAndServe("localhost:81", nil)
}
Thanks!
PS: Very tedious to add four space before every line of code in stackoverflow especially when you are copy pasting. Didn't find it very user friendly or is there an easier way?
Writing to the ResponseWriter (by calling Execute) before reading the value from the request is clearing it out.
You can see this in action if you use this request handler:
func GeneralHandler(w http.ResponseWriter, r *http.Request) {
fmt.Println(r.Method)
fmt.Println(r.URL)
fmt.Println("before",r.FormValue("username"))
index.Execute(w, nil)
if r.Method == "POST" {
fmt.Println("after",r.FormValue("username"))
}
}
This will print out before and after. However, in this case:
func GeneralHandler(w http.ResponseWriter, r *http.Request) {
fmt.Println(r.Method)
fmt.Println(r.URL)
index.Execute(w, nil)
if r.Method == "POST" {
fmt.Println("after",r.FormValue("username"))
}
}
The after value will be blank.
According to the documentation for html/template the second argument to Execute should be the data you want to put in the template.
Add a {{.}} somewhere in your template and then pass the string you want printed in as the second argument. It should get rendered as part of the template.