Search code examples
filterclojuretagsselmer

Selmer: How does one apply filters in a custom tag?


I am playing around with the Selmer library (version 1.12.33) and have constructed a simple custom tag. I want to modify this tag further to allow the use of filters in a similar vein how some standard tags, e.g. if, for, script, and style seem to allow it.

Seems the documentation doesn't cover it; does anyone know how to do this?

Here is some (very simplified) example code distilling the essence:

1. Defining the custom tag:

(selmer.parser/add-tag! :hello
  (fn [[arg & _] ctx] ; use only first argument
    (let [[name & filters] (clojure.string/split arg #"\|")] ; separate arg1 from appended filter(s)
      (format "Hi, %s!" (or ((keyword name) ctx) name))))) ; look up in context map, else use as-is

Obviously, I need to use filters here somehow, but I don't know how...

2. Rendering the text

(def myctx {:greet/name "world"})
(selmer.parser/render "{{greet/name|upper|safe}}" myctx)
   ; SUCCESS: expected & actual: WORLD
(selmer.parser/render "{% hello greet/name|upper|safe %}" myctx)
   ; FAIL: Expected: Hi, WORLD!, actual: Hi, world!

Solution

  • I guess the erm, obvious way would be to co-opt Selmer to do its stuff on only the input arg, without trying to re-invent Selmer's wheel. The custom tag would then be something like:

    (selmer.parser/add-tag! :hello
      (fn [[arg & _] ctx] ; use only first argument
        (let [name (selmer.parser/render (str "{{" arg "}}") ctx)]
          (format "Hello, %s!" name))))
    

    Too obvious? I would be grateful for a better answer or even comments regarding pitfalls with this method, as I am fairly new to Clojure and don't trust my own insight yet.