3

Is it possible to subscript strings in django templates ?

What i mean is doing

print "hello"[:3]
=> hel

in django templates.

Writing {{ stringVar[:10] }} throws

TemplateSyntaxError: Could not parse the remainder: '[:10]'  from 'stringVar[:10]'
1
  • Incidentally the answer was an inbuilt filter. So I think I will remove the sentence "Is there an inbuilt way to do this other than writing filters ?" Commented Dec 2, 2011 at 8:13

1 Answer 1

7

You can, but the syntax is slightly different as what you're used to. Use slice:

{{ stringVar|slice:":2" }}

This will give you the first 2 elements from the list (or the first two chars from a string).

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.