GO · 파일/IO
템플릿 (html/template)
html/template으로 안전한 HTML을 생성합니다. XSS 자동 방지와 템플릿 상속을 지원합니다.
파일/IO중급templatehtmlxssrendering
핵심 설명
html/template으로 안전한 HTML을 생성합니다. XSS 자동 방지와 템플릿 상속을 지원합니다.
Go code
package main
import (
"html/template"
"os"
)
const tmpl = `<!DOCTYPE html>
<html>
<head><title>{{.Title}}</title></head>
<body>
<h1>{{.Title}}</h1>
{{range .Items}}
<div class="item">
<strong>{{.Name}}</strong>: {{.Price}}원
</div>
{{end}}
{{if .ShowFooter}}
<footer>© 2024</footer>
{{end}}
<!-- XSS 자동 이스케이프 -->
<p>입력: {{.UserInput}}</p>
</body>
</html>`
type PageData struct {
Title string
Items []struct{ Name string; Price int }
ShowFooter bool
UserInput string
}
func main() {
t := template.Must(template.New("page").Parse(tmpl))
data := PageData{
Title: "상품 목록",
Items: []struct{ Name string; Price int }{
{"Go 책", 35000}, {"키보드", 89000},
},
ShowFooter: true,
UserInput: "<script>alert('xss')</script>",
}
t.Execute(os.Stdout, data)
}학습 팁
html/template은 컨텍스트에 따라 자동으로 HTML, JS, URL 이스케이프를 적용합니다. XSS를 원천 차단합니다.
주의할 점
text/template은 이스케이프를 하지 않습니다. HTML 출력에는 반드시 html/template을 사용하세요.
자주 묻는 질문
템플릿 (html/template)란 무엇인가요?
html/template 으로 안전한 HTML을 생성합니다. XSS 자동 방지와 템플릿 상속을 지원합니다.
템플릿 (html/template) 학습 시 주의할 점은 무엇인가요?
text/template 은 이스케이프를 하지 않습니다. HTML 출력에는 반드시 html/template 을 사용하세요.
Continue Learning
Go 학습을 이어가세요
총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.