TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to GO

Golang html template Example

Use the html/template module to implement an HTML generator that inserts values into tags.
HTML template. Websites are under nearly constant attack. Most of these are automated. To prevent a certain kind of attack, a special Go module called "html/template" is available.
With this module, we pass HTML markup to a Parse() method. Then when we call Execute(), we insert values into special substitutions. Characters are escaped.
An example program. We must use a Writer with the "html/template" package. This program uses the bufio package to create a Writer (with NewWriter).File

And: Once the Writer is created, we can create a new template with template.New. We provide a name for the template ("example").

Parse: We call this func and pass a specially-formatted string. The substitution comes after the word "Hello" here.

Execute: Here we pass the Writer, followed by the values to be inserted into the HTML template.

Golang program that uses html template package main import ( "bufio" "html/template" "os" ) func main() { // Create a file. f, _ := os.Create("C:\\programs\\file.txt") // New writer. out := bufio.NewWriter(f) // Create template and parse it. tmpl, _ := template.New("example").Parse("<p>Hello {{.}}</p>") // Insert string into substitution. tmpl.Execute(out, "Friend") // Done. out.Flush() } Output <p>Hello Friend</p>
Notes, result of program. To see the result of the program, open the file it wrote to—you will want to adjust the path before you execute the program.
Notes, continued. The HTML is fully generated. The string "Friend" was placed in the HTML where the substitution marker was originally present.
A review. Generating HTML is (for the most part) not an interesting problem. But it is a useful thing to do—HTML is perhaps the most widely used document format in the world.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf