开发者

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 i开发者_如何学JAVAnto 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..


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.


You can have your custom tag apply "class" values for your Javascript to look for. Include your Javascript as a regular .js <script> import, and have it use a load-time function to find your elements and manipulate them as necessary.

So for example if your tag creates a <div>, you can have it do this:

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

Your Javascript can then do this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜