mmontone / djula

Common Lisp port of the Django templating language
http://mmontone.github.io/djula/djula
MIT License
152 stars 21 forks source link

Implement divisibleby or modulus equivalent #50

Closed mateusfccp closed 4 years ago

mateusfccp commented 5 years ago

I'm missing the possibility of modulus operating on Djula templates.

On Django, it can be done with divisibleby. Ex: {% if forloop.counter0|divisibleby:4 %}. However, I can't do this on Djula. Obviously, forloop.counter0 % 4 also won't work, as % is a special character.

Would it be possible to implement modulus operator on templates?

mateusfccp commented 5 years ago

I tried making something by my own but had not succeeded.

Tentative 1:

(def-filter :divisibleby (it n)
  (= (mod it (parse-integer n)) 0))

In this case, as it returns a boolean, I tryied using inside if tag. {% if forloop.counter|divisibleby:2 %} ... {% endif %}. However, I think if can't handle vars with flags. Also, there's no reference of filters that returns bool on the source, so I had not a reference.

I got a parse error: Cannot extend the template ~A because there was an error parsing the template file ~A.

If I use as a print expression ({{ forloop.counter|divisibleby:2 }}), it works as expected, printing T or nothing.

Tentative 2:

(def-filter :modulus (it n)
  (mod it (parse-integer n)))

In the second tentative, as in the first one, the output was correct when printing it with {{}}, but got the same error when trying to use it inside a if ({% if forloop.counter|module:2 == 0 %}).

mmontone commented 5 years ago

There's no support for filters/operations in if expressions. Not sure about what would be the most pragmatic approach to achieve what you need. Perhaps it would be worth it to implement it, I don't know.

duikboot commented 4 years ago

It is implemented in the master branch now.

mateusfccp commented 4 years ago

Nice, @duikboot.

Closing the issue.