Improving the Markdown Preview Tool with Templates

Powerful Command-Line Applications in Go — by Ricardo Gerardi (36 / 127)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Cleaning Up Temporary Files | TOC | Exercises 👉

As the final improvement to the mdp tool, you’ll update the way it writes the final HTML file. You currently have the HTML header and footer hard-coded in the program. It’s a good start, but it makes the tool less flexible and harder to maintain. To address this issue, use the html/template package to create a data-driven template that allows you to inject code at predefined places at runtime.

Templates are perfect in situations where you need to write files with some fixed content and you want to inject dynamic data at runtime. Go provides another template package called text/template, but you should use the html/template when writing HTML content. Both packages share a similar interface, so understanding one makes it easier to use the other.

Let’s build an implementation that provides a hardcoded default template but also allows the user to specify their own alternate version using a command-line flag -t. By doing this, we allow users to change the preview format and appearance without changing the application code, increasing its flexibility and maintainability.

Start by adding the package html/template to the import list as usual:

workingFiles/mdp.v5/main.go

​ ​import​ (
​ ​"bytes"​
​ ​"flag"​
​…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.