shithub: hugo

Download patch

ref: be0cbeee7fb9b6e8af12745971ff80e86e0d3d32
parent: bec90e085055ef96cbd6a17604cf1020c2c82f24
author: bep <[email protected]>
date: Mon May 11 08:28:44 EDT 2015

Add absURL template func

Fixes #1106

--- a/helpers/url.go
+++ b/helpers/url.go
@@ -138,11 +138,20 @@
 	base.Path = path.Join(base.Path, p.Path)
 
 	// path.Join will strip off the last /, so put it back if it was there.
-	if strings.HasSuffix(p.Path, "/") && !strings.HasSuffix(base.Path, "/") {
+	hadTrailingSlash := (plink == "" && strings.HasSuffix(host, "/")) || strings.HasSuffix(p.Path, "/")
+	if hadTrailingSlash && !strings.HasSuffix(base.Path, "/") {
 		base.Path = base.Path + "/"
 	}
 
 	return base
+}
+
+// AbsURL creates a absolute URL from the relative path given and the BaseURL set in config.
+func AbsURL(path string) string {
+	if strings.HasPrefix(path, "http") || strings.HasPrefix(path, "//") {
+		return path
+	}
+	return MakePermalink(string(viper.GetString("BaseURL")), path).String()
 }
 
 // AddContextRoot adds the context root to an URL if it's not already set.
--- a/helpers/url_test.go
+++ b/helpers/url_test.go
@@ -1,6 +1,7 @@
 package helpers
 
 import (
+	"github.com/spf13/viper"
 	"github.com/stretchr/testify/assert"
 	"strings"
 	"testing"
@@ -20,6 +21,28 @@
 
 	for _, test := range tests {
 		output := URLize(test.input)
+		if output != test.expected {
+			t.Errorf("Expected %#v, got %#v\n", test.expected, output)
+		}
+	}
+}
+
+func TestAbsURL(t *testing.T) {
+	tests := []struct {
+		input    string
+		baseURL  string
+		expected string
+	}{
+		{"/test/foo", "http://base/", "http://base/test/foo"},
+		{"", "http://base/ace/", "http://base/ace/"},
+		{"/test/2/foo/", "http://base", "http://base/test/2/foo/"},
+		{"http://abs", "http://base/", "http://abs"},
+		{"//schemaless", "http://base/", "//schemaless"},
+	}
+
+	for _, test := range tests {
+		viper.Set("BaseURL", test.baseURL)
+		output := AbsURL(test.input)
 		if output != test.expected {
 			t.Errorf("Expected %#v, got %#v\n", test.expected, output)
 		}
--- a/tpl/template_funcs.go
+++ b/tpl/template_funcs.go
@@ -1196,6 +1196,7 @@
 		"safeHTML":    SafeHTML,
 		"safeCSS":     SafeCSS,
 		"safeURL":     SafeURL,
+		"absURL":      func(a string) template.HTML { return template.HTML(helpers.AbsURL(a)) },
 		"markdownify": Markdownify,
 		"first":       First,
 		"where":       Where,