简体   繁体   English

自定义Django标记和jQuery

[英]Custom Django tag & jQuery

I'm new to Django. 我是Django的新手。 Today I created some Django custom tags which is not that hard. 今天我创建了一些Django自定义标签并不难。 But now I wonder what is the best way to include some jQuery or some Javascript code packed into my custom tag definition. 但现在我想知道在我的自定义标签定义中包含一些jQuery或一些Javascript代码的最佳方法是什么。 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. 因此,假设它将为Facebox插件创建特定的HTML输出。 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.. 也许我错过了什么......

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. 您可以让自定义标记为您的Javascript应用“类”值。 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. 将您的Javascript包含为常规.js <script>导入,并让它使用加载时功能来查找元素并根据需要对其进行操作。

So for example if your tag creates a <div> , you can have it do this: 因此,例如,如果您的标记创建了<div> ,则可以执行此操作:

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

Your Javascript can then do this: 您的Javascript可以这样做:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM