I've created a custom tag that I want to use, but Django can't seem to find it. My templatetags
directory is set up like this:
pygmentize.py
from pygments import highlight from pygments.lexers import get_lexer_by_name from django import template from pygments.formatters.other import NullFormatter register = template.Library() @register.tag(name='code') def do_code(parser,token): code = token.split_contents()[-1] nodelist = parser.parse(('endcode',)) parser.delete_first_token() return CodeNode(code,nodelist) class CodeNode(template.Node): def __init__(self,lang,code): self.lang = lang self.nodelist = code def render(self,context): code = self.nodelist.render(context) lexer = get_lexer_by_name('python') return highlight(code,lexer,NullFormatter())
I am trying to use this tag to render code in gameprofile.html
.
gameprofile.html
(% load pygmentize %} {% block content %} <title>{% block title %} | {{ game.title }}{% endblock %}</title> <div id="gamecodecontainer"> {% code %} {{game.code}} {% endcode %} </div> {% endblock content %}
When I navigate to gameprofile.html
, I get an error:
Invalid block tag on line 23: 'code', expected 'endblock'. Did you forget to register or load this tag?
Create a custom template tagUnder the application directory, create the templatetags package (it should contain the __init__.py file). For example, Django/DjangoApp/templatetags. In the templatetags package, create a . py file, for example my_custom_tags, and add some code to it to declare a custom tag.
You can extend the template engine by defining custom tags and filters using Python, and then make them available to your templates using the {% load %} tag.
Django Code The template tags are a way of telling Django that here comes something else than plain HTML. The template tags allows us to to do some programming on the server before sending HTML to the client.
The error is in this line: (% load pygmentize %}
, an invalid tag. Change it to {% load pygmentize %}
For Django 2.2 up to 3, you have to load staticfiles in html template first before use static keyword
{% load staticfiles %} <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
For other versions use static
{% load static %} <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
Also you have to check that you defined STATIC_URL in setting.py
At last, make sure the static files exist in the defined folder
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With