23

I am using the lxml library to define a variable (category) in a view. lxml provides a method .get to retrieve custom attributes. I'd like to use it in the template like so:

{{ category.get("foo") }} 

I know that when using template variables it is unnecessary to use parenthesis, but I get the following error:

{{ category.get "foo" }}

Could not parse the remainder: ' "foo"' from 'category.get "foo"'

I'm assuming that there is something wrong with my syntax but google has been no help. The django docs say that methods are looked up by using a .

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
  • The syntax used in Django template filters is ":" for arguments, so I think if someone were to implement this, it would be {{ category.get:foo }}. But, it doesn't exist. Maybe you should add it? – slacy Oct 23 '09 at 04:20
  • Possible duplicate of [How to call function that takes an argument in a Django template?](http://stackoverflow.com/questions/2468804/how-to-call-function-that-takes-an-argument-in-a-django-template) – Ciro Santilli OurBigBook.com May 11 '16 at 22:18

3 Answers3

32

You can't pass an argument to a callable attribute like this. Either pull the value in the view, or write a custom template tag to do it.

Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662
15

I agree with the philosophy of separating logic from design, but there's an exception. I am currently writing a get_image(height=xxx, width=xxx) method for a model. Clearly, it should be up to the template designer to decide the size of the image as the last stage. Though I suppose the correct thing to do is write a custom tag, but why restrict?

Joe
  • 159
  • 1
  • 2
12

Here I wrote a hack to call a function and pass the arguments http://www.sprklab.com/notes/13-passing-arguments-to-functions-in-django-template/

Pavel
  • 121
  • 1
  • 3
  • This looks somehow like mixing code and content, almost the same way PHP does that. What do you think? – dotz Apr 25 '13 at 08:31