ref: fde47c5eb9435083cc492b8648517b374eb60c6b
parent: 3d09de891072985e6c59f899f09132a76d44f7cd
author: Cameron Moore <[email protected]>
date: Fri Nov 20 13:59:54 EST 2015
Add shortcode IsNamedParams property It would be helpful to know whether a shortcode was called with positional or named parameters. This commit adds a boolean `IsNamedParams` property to the `ShortcodeWithPage` struct.
--- a/hugolib/shortcode.go
+++ b/hugolib/shortcode.go
@@ -31,9 +31,10 @@
)
type ShortcodeWithPage struct {
- Params interface{}
- Inner template.HTML
- Page *Page
+ Params interface{}
+ Inner template.HTML
+ Page *Page
+ IsNamedParams bool
}
func (scp *ShortcodeWithPage) Ref(ref string) (string, error) {
@@ -189,12 +190,16 @@
const innerCleanupExpand = "$1"
func renderShortcode(sc shortcode, p *Page, t tpl.Template) string {
- var data = &ShortcodeWithPage{Params: sc.params, Page: p}
tmpl := getShortcodeTemplate(sc.name, t)
if tmpl == nil {
jww.ERROR.Printf("Unable to locate template for shortcode '%s' in page %s", sc.name, p.BaseFileName())
return ""
+ }
+
+ data := &ShortcodeWithPage{Params: sc.params, Page: p}
+ if sc.params != nil {
+ data.IsNamedParams = reflect.TypeOf(sc.params).Kind() == reflect.Map
}
if len(sc.inner) > 0 {
--- a/hugolib/shortcode_test.go
+++ b/hugolib/shortcode_test.go
@@ -119,6 +119,20 @@
CheckShortCodeMatch(t, `{{< img src = "one" class = "aspen grove" >}}`, `<img src="one" class="aspen grove">`, tem)
}
+func TestIsNamedParamsSC(t *testing.T) {
+ tem := tpl.New()
+ tem.AddInternalShortcode("byposition.html", `<div id="{{ .Get 0 }}">`)
+ tem.AddInternalShortcode("byname.html", `<div id="{{ .Get "id" }}">`)
+ tem.AddInternalShortcode("ifnamedparams.html", `<div id="{{ if .IsNamedParams }}{{ .Get "id" }}{{ else }}{{ .Get 0 }}{{end}}">`)
+
+ CheckShortCodeMatch(t, `{{< ifnamedparams id="name" >}}`, `<div id="name">`, tem)
+ CheckShortCodeMatch(t, `{{< ifnamedparams position >}}`, `<div id="position">`, tem)
+ CheckShortCodeMatch(t, `{{< byname id="name" >}}`, `<div id="name">`, tem)
+ CheckShortCodeMatch(t, `{{< byname position >}}`, `<div id="error: cannot access positional params by string name">`, tem)
+ CheckShortCodeMatch(t, `{{< byposition position >}}`, `<div id="position">`, tem)
+ CheckShortCodeMatch(t, `{{< byposition id="name" >}}`, `<div id="error: cannot access named params by position">`, tem)
+}
+
func TestInnerSC(t *testing.T) {
tem := tpl.New()
tem.AddInternalShortcode("inside.html", `<div{{with .Get "class"}} class="{{.}}"{{end}}>{{ .Inner }}</div>`)