1

So I'm looking to do something like this to keep things DRY:

{% with share_text=author.name + "released" + book.title + "via:myapp" %}
    do stuff with {{share_text}}
{% endwith %}

However, I'm getting Django template errors like "could not parse remainder" and "with received invalid operator +".

2
  • 3
    The idea is not to do this in a template (Django templates deliberately are less expressive than Python code, to avoid writing business logic in the template), but in a view, or use {{author.name}}released{{book.title}}, etc. Commented Aug 24, 2018 at 10:44
  • 1
    @WillemVanOnsem while I wholefully agree with the whole idea of avoiding business code in templates, it doesn't apply here - this is obviously presentation - and sometime you have to reuse the same formatted string in different places in a template and don't want to repeat yourself. Commented Aug 24, 2018 at 10:50

1 Answer 1

9

Django template language is NOT python (ever if it sometimes looks a bit similar), so don't expect python code to work here. Use template filters / tags. In your case the builtin add templatefilter should work:

{% with share_text=author.name|add:"released"|add:book.title|add:"via:myapp" %}

but please carefully read the limitations and gotchas mentioned in the doc. Else you can write your own custom filter or templatetag, that's really easy.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.