-1

The following code works in an application:

user.tweets.order_by(Tweet.message)

The following code works in a jinja2 template:

{% for tweet in user.tweets %}

But the following code fails in a template:

{% for tweet in user.tweets.order_by(Tweet.message) %}

Is there a cleaner way to sort the tweets in a jinja2 template, other than adding the following method to the User class?

def tweets_by_message(self):
    return user.tweets.order_by(Tweet.message)

There is nothing wrong with that method, but adding a little method every time I need a different order doesn't sound right.

stenci
  • 8,290
  • 14
  • 64
  • 104
  • What do you mean at the beginning when you say "The following code works in an application"? What sort of application? Ref the docs for jinja2 filters, I think you need to user the sort filter and the attribute param: http://jinja.pocoo.org/docs/dev/templates/#sort – Tom Dalton Jan 31 '15 at 00:49

2 Answers2

-1

Maybe you can drop Tweet into the template context. Or better yet, use a context processor to dump all your models into the template context so they're available all the time.

@app.context_processor
def _inject_models():
    return {
        'Tweet': Tweet,
        'User': User,
        'Foo': Foo,
    }

I don't know if this works, but might be worth a shot?

coleifer
  • 24,887
  • 6
  • 60
  • 75
-1

I guess you are looking for this:

{% for tweet in user.tweets|sort(attribute='message') %}
Taxellool
  • 4,063
  • 4
  • 21
  • 38