Search code examples
jquerypythondjangodjango-custom-tags

Custom Django tag & jQuery


I'm new to Django. Today I created some Django custom tags which is not that hard. But now I wonder what is the best way to include some jQuery or some Javascript code packed into my custom tag definition. What is the regular way to include a custom library into my code? For example:

{% faceboxify item %}

So assume that it'll create a specific HTML output for Facebox plugin. I just want to learn some elegant way to import this plugin into my code. I want the above definition to be enough for all functionality. Is there any way to do it? I couldn't find any example. Maybe I'm missing something..


Solution

  • From the documentation you can see that writing template tags involves writing a target function and a renderer. So I'm assuming your current code looks like this:

    def my_tag(parser, token):
      # ... some code
      return MyNode(...)
    
    class MyNode(template.Node):
      def render(self, context):
         # here is where you write your <script> tags
    

    So essentially what you have to do is to hang a variable under the context so you can know if for that specific request you've already included the code to load all your needed scripts.

    class MyNode(template.Node):
      def render(self, context):
         if '_included_faceboxify_deps' in context:
           # render your <script> dependency includes
           context['_included_faceboxify_deps'] = True
         # render your <script>s that are specific for this call
    

    This should do the trick. It's not as elegant as including your dependencies in the top of the page, but it's enough not to include them for every time you need to call them.