Django & jQuery Custom Tag

I am new to Django. Today I created some custom Django tags that are not so difficult. But now I'm wondering what is the best way to include some jQuery or some Javascript code packaged in my custom tag definition. What is the regular way to include a custom library in my code? For instance:

{% faceboxify item %}

Suppose it creates a specific HTML output for the Facebox plugin. I just want to learn an elegant way to import this plugin into my code. I want the above definition to be sufficient for all functions. Is there any way to do this? I could not find a single example. Maybe I missed something.

+3
source share
2 answers

From the documentation you can see that the tags of the letter templates include a record of the objective function and visualization tools. Therefore, I assume that your current code is as follows:

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 you need to hang the variable in context so that you can know if for this particular request you have already included code to load all the necessary 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

That should do the trick. This is not as elegant as including your dependencies at the top of the page, but just not including them every time you need to name them.

+2
source

"" Javascript . Javascript .js <script> import .

, , <div>, :

<div class='faceboxify'>
  <!-- whatever -->
</div>

Javascript :

$(function() {
  $('div.faceboxify').each(function() {
    // ... stuff to be done to your "faceboxify" divs
  });
});
0

Source: https://habr.com/ru/post/1749825/


All Articles