diff options
author | Noah Campbell <noahcampbell@gmail.com> | 2013-09-28 23:05:16 -0700 |
---|---|---|
committer | Noah Campbell <noahcampbell@gmail.com> | 2013-09-28 23:05:16 -0700 |
commit | f34ea6108d259caec04b4f7b325c91db071e78f8 (patch) | |
tree | 7929c5f6d1eedb781084ee54d2dccb4f8c0f197e /transform | |
parent | db50154e75cfb1100651b7521370f54a0695872e (diff) |
Add the ability to set navbar li class to active
First cut at doing post html processing. This utility can be used to
mark pages as active.
Diffstat (limited to 'transform')
-rw-r--r-- | transform/nav.go | 28 | ||||
-rw-r--r-- | transform/nav_test.go | 60 |
2 files changed, 88 insertions, 0 deletions
diff --git a/transform/nav.go b/transform/nav.go new file mode 100644 index 000000000..c3dfe7900 --- /dev/null +++ b/transform/nav.go @@ -0,0 +1,28 @@ +package transform + +import ( + htmltran "code.google.com/p/go-html-transform/html/transform" + "io" + "fmt" +) + +type NavActive struct { + Section string +} + +func (n *NavActive) Apply(r io.Reader, w io.Writer) (err error) { + var tr *htmltran.Transformer + + if n.Section == "" { + _, err = io.Copy(w, r) + return + } + + if tr, err = htmltran.NewFromReader(r); err != nil { + return + } + + tr.Apply(htmltran.ModifyAttrib("class", "active"), fmt.Sprintf("li[data-nav=%s]", n.Section)) + + return tr.Render(w) +} diff --git a/transform/nav_test.go b/transform/nav_test.go new file mode 100644 index 000000000..997fe33f6 --- /dev/null +++ b/transform/nav_test.go @@ -0,0 +1,60 @@ +package transform + +import ( + "bytes" + "strings" + "testing" +) + +const HTML_WITH_NAV = `<!DOCTYPE html> +<html> +<head></head> +<body> +<nav> + <ul class="nav navbar-nav"> + <li data-nav="section_1"><a href="#">Section 1</a></li> + <li data-nav="section_2"><a href="#">Section 2</a></li> + </ul> +</nav> +</body> +</html> +` +const EXPECTED_HTML_WITH_NAV_1 = `<!DOCTYPE html><html><head></head> +<body> +<nav> + <ul class="nav navbar-nav"> + <li data-nav="section_1"><a href="#">Section 1</a></li> + <li data-nav="section_2" class="active"><a href="#">Section 2</a></li> + </ul> +</nav> + + +</body></html>` + +func TestDegenerateNoSectionSet(t *testing.T) { + var ( + tr = new(NavActive) + out = new(bytes.Buffer) + ) + + if err := tr.Apply(strings.NewReader(HTML_WITH_NAV), out); err != nil { + t.Errorf("Unexpected error in NavActive.Apply: %s", err) + } + + if out.String() != HTML_WITH_NAV { + t.Errorf("NavActive.Apply should simply pass along the buffer unmodified.") + } +} + +func TestSetNav(t *testing.T) { + tr := &NavActive{Section: "section_2"} + out := new(bytes.Buffer) + if err := tr.Apply(strings.NewReader(HTML_WITH_NAV), out); err != nil { + t.Errorf("Unexpected error in Apply() for NavActive: %s", err) + } + + expected := EXPECTED_HTML_WITH_NAV_1 + if out.String() != expected { + t.Errorf("NavActive.Apply output expected and got:\n%q\n%q", expected, out.String()) + } +} |