Commit 86f36bdb authored by Miek Gieben's avatar Miek Gieben

Add .Markdown directive

This allows any template to use:
{{.Markdown "filename"}} which will convert the markdown contents
of filename to HTML and then include the HTML in the template.
parent 79db9392
...@@ -9,6 +9,8 @@ import ( ...@@ -9,6 +9,8 @@ import (
"strings" "strings"
"text/template" "text/template"
"time" "time"
"github.com/russross/blackfriday"
) )
// This file contains the context and functions available for // This file contains the context and functions available for
...@@ -190,3 +192,17 @@ func (c Context) StripExt(path string) string { ...@@ -190,3 +192,17 @@ func (c Context) StripExt(path string) string {
func (c Context) Replace(input, find, replacement string) string { func (c Context) Replace(input, find, replacement string) string {
return strings.Replace(input, find, replacement, -1) return strings.Replace(input, find, replacement, -1)
} }
// Markdown returns the HTML contents of the markdown contained in filename
// (relative to the site root).
func (c Context) Markdown(filename string) (string, error) {
body, err := c.Include(filename)
if err != nil {
return "", err
}
renderer := blackfriday.HtmlRenderer(0, "", "")
extns := blackfriday.EXTENSION_TABLES | blackfriday.EXTENSION_FENCED_CODE | blackfriday.EXTENSION_STRIKETHROUGH | blackfriday.EXTENSION_DEFINITION_LISTS
markdown := blackfriday.Markdown([]byte(body), renderer, extns)
return string(markdown), nil
}
...@@ -92,6 +92,45 @@ func TestIncludeNotExisting(t *testing.T) { ...@@ -92,6 +92,45 @@ func TestIncludeNotExisting(t *testing.T) {
} }
} }
func TestMarkdown(t *testing.T) {
context := getContextOrFail(t)
inputFilename := "test_file"
absInFilePath := filepath.Join(fmt.Sprintf("%s", context.Root), inputFilename)
defer func() {
err := os.Remove(absInFilePath)
if err != nil && !os.IsNotExist(err) {
t.Fatalf("Failed to clean test file!")
}
}()
tests := []struct {
fileContent string
expectedContent string
}{
// Test 0 - test parsing of markdown
{
fileContent: "* str1\n* str2\n",
expectedContent: "<ul>\n<li>str1</li>\n<li>str2</li>\n</ul>\n",
},
}
for i, test := range tests {
testPrefix := getTestPrefix(i)
// WriteFile truncates the contentt
err := ioutil.WriteFile(absInFilePath, []byte(test.fileContent), os.ModePerm)
if err != nil {
t.Fatal(testPrefix+"Failed to create test file. Error was: %v", err)
}
content, _ := context.Markdown(inputFilename)
if content != test.expectedContent {
t.Errorf(testPrefix+"Expected content [%s] but found [%s]. Input file was: %s", test.expectedContent, content, inputFilename)
}
}
}
func TestCookie(t *testing.T) { func TestCookie(t *testing.T) {
tests := []struct { tests := []struct {
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment