Entries tagged 'SQLAlchemy'
Is this Twig or Jinja? Maybe both!
A project I have been playing around with the last couple of weekends has been making a Python version of this site. The code, which is very rough because I barely know what I’m doing and I’m in the hacking-it-together phase as opposed to trying to make it pretty, is in this GitHub repository.
I am using the Flask framework with SQLAlchemy and Jinja.
I was interested to see if I could just use the same templates as my PHP version, which uses Twig, but there have been a few sticking points:
- The Twig
escape
filter takes an argument to more finely control the context it is being used in so it knows how to escape within HTML, or a URI, or an HTML attribute. Jinja’sescape
doesn’t take an argument. I was able to override it take an extra argument, but mostly ignore it for now. - Jinja doesn’t have Twig’s ternary
?:
operator. Not surprising, Python doesn’t either. I rewrote those bits of templates to use slightly more verboseif
blocks. - Jinja doesn’t have Twig’s string comparators like
matches
andstarts with
. Looks like I can get rid of the need for them, but I just punted on those for now. - Jinja doesn’t have a
block()
function. I think I can also avoid needing it. - Jinja’s
url_for()
method expects a more Python-ic argument list, likeurl_for('route', var = 'value')
but Twig uses a dictionary likeurl_for('route', { 'var' : 'value' })
. I was able to override Jinja’s version to handle this, too. - I’ll need to implement versions of Twig’s
date()
function and filter.
I had cobbled together a way on the Twig side to let me store some templates (side navigation, the “Hire me!” message on the front page) in the database, so my next trick is going to implement template loaders for both the PHP and Python versions so that is more cleanly abstracted. I have the Python side of that done already.
I hope to eventually create a Rust version of this, too, and it will be interesting to see what new complications using Tera will bring.