Skip to content

Accessing a single string char at an index has no output #633

Open

Description

@blx

Hello, thanks for this library! I ran into a small issue that can be worked around easily, but is still a point of incompatibility with python jinja2. (Although, it doesn't work in Django templates either (see at the end), so maybe it's out of scope.)

In jinja2, I can interpolate a single character of a string:

>>> import jinja2
>>> jinja2.__version__
'2.11.3'
>>> jinja2.Template("{{ x[0] }}").render({'x': 'stuff'})
's'

whereas in jinjava (2.5.6 from maven), this is empty:

Clojure 1.10.3
user=> (import '[com.hubspot.jinjava Jinjava])
com.hubspot.jinjava.Jinjava
user=> (.render (Jinjava.) "{{ x[0] }}" {"x" "stuff"})
""

(This is the clojure shell, but it's importing the same java library, and I first observed this behaviour in a pure-java service.)


I can get around this by using a slice instead of a single index:

user=> (.render (Jinjava.) "{{ x[0:1] }}" {"x" "stuff"})
"s"

which works equivalently in python jinja2:

>>> jinja2.Template("{{ x[0:1] }}").render({'x': 'stuff'})
's'

For sake of comparison, indexing a string doesn't seem to work at all in django templates, whether it's a single character or a slice:

>>> # Setup
>>> from django.conf import settings
>>> settings.configure(DEBUG=True, TEMPLATE_DEBUG=True, TEMPLATE_LOADERS=(), TEMPLATES=[{'BACKEND':'django.template.backends.django.DjangoTemplates', 'OPTIONS':{'loaders':[('django.template.loaders.locmem.Loader', {'main': ''})]}}])
>>> import django
>>> django.setup()
>>> from django.template import Context, Template
>>> 
>>> Template('{{ x[0:5] }}').render(Context({'x': 'stuff'}))
Traceback (most recent call last):
...
django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: '[0:5]' from 'x[0:5]'
>>> Template('{{ x[0] }}').render(Context({'x': ['stuff', 1, 2, 3, 4, 5, 6]}))
Traceback (most recent call last):
...
django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: '[0]' from 'x[0]'

although I can use the slice filter instead (which does python iterable slicing, not the chunking of jinja's slice):

>>> Template('{{ x|slice:1 }}').render(Context({'x': 'stuff'}))
's'
>>> Template('{{ x|slice:"0:2" }}').render(Context({'x': 'stuff'}))
'st'

Activity

  1. added a commit that references this issue on Oct 16, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions