user1261774
user1261774

Reputation: 3695

django writing my first custom template tag and filter

I am attempting to write a simple django Custom template tags and filters to replace a html break (< b r / >) with a line space on a template.

I have followed the django docs, but I am getting the following error, which I don't know how to solve.

The error I have is:

x_templates_extra' is not a valid tag library: Template library x_templates_extra not found, tried django.templatetags.x_templates_extra,django.contrib.staticfiles.templatetags.x_templates_extra,django.contrib.admin.templatetags.x_templates_extra,django.contrib.flatpages.templatetags.x_templates_extra,rosetta.templatetags.x_templates_extra,templatetag_handlebars.templatetags.x_templates_extra,globalx.common.templatetags.x_templates_extra,rollyourown.seo.templatetags.x_templates_extra,debug_toolbar.templatetags.x_templates_extra

Here is what I have done:

1. created a templatetags directory, at the same level as models.py, views.py, etc

2. created a __init__.py file inside the templatetags directory to ensure the directory is treated as a Python package

3. created a file inside the templatetags directory called x_templates_extra.py

4. added the load tag to the template: {% load x_templates_extra %}

5. added the tag to the template: {{ x_detail.x_details_institution_name|safe|replace:"<br />"|striptags|truncatechars:popover_string_length_20 }}

6. Added the following code to the file x_templates_extra.py:

from django import template

register = template.Library()

def replace(value, arg):
   """Replaces all values of arg from the given string with a space."""
    return value.replace(arg, ' ')

Question:

The docs state that: So, near the top of your module, put the following:

from django import template

register = template.Library()

I have put the import & register lines in my file called: called x_templates_extra.py. Is that correct?

Also I am not sure what to put in the INSTALLED_APPS to make the load work.

Tried many things, but I am now going in circles, so I do need help.

Thanks.

Upvotes: 2

Views: 1067

Answers (2)

AmiNadimi
AmiNadimi

Reputation: 5725

If your App name is foo and your tag folder name is goo then in settings.py you should have :

INSTALLED_APPS = [
'foo',
'foo.goo'

]

both your app and your tag folder which is under your app package Django Project are needed there.

-> foo
    ---> models.py
    ---> views.py
    ---> goo
      -----> __init__.py
      -----> app_filters.py

Upvotes: 0

user1261774
user1261774

Reputation: 3695

Finally got it to work.

adding the correct app name to the INSTALLED APPS was th eissue.

Upvotes: 1

Related Questions