Malcolm Tredinnick wrote:
> On Tue, 2007-06-12 at 05:44 -0400, Andrew R wrote:
>> I have to admit, though, that I think adding a custom filter should be as 
>> simple
>> as this code alone:
>>
>>> from django.template import Library
>>>
>>> register = Library()
>>>
>>> @register.filter
>>> def javadoc_filter(value, arg):
>>>    return "whatever"
>>>
>> I think part of my confusion was that my subconscious thinking was "my filter
>> code has been imported (I can see the .pyc) so I know python has seen it, and
>> therefore the filter is registered with the library, so I should be able to 
>> use
>> it.".
> 
> ...
> 
> If you come up with a patch to make filter registration remember the
> path to the file so that the "load" template tag can find it later, we'd
> certainly consider it.

Malcolm - you mentioned a patch to support this - I've provided one below.

With the patch, I can write a filter like this in my main program (or anywhere):

  def filter_rst_h1(value, arg='-'):
    "Write a single underline under the text"
    line=arg * len(value)
    return "%s\n%s" % (value, line)

To use this filter, all I need is this:

  from django.template import BuiltinLibrary # <-- NEW!
        
  # set up extra library of routines for later use...
  library = BuiltinLibrary()
  library.filter('filter_rst_h1', filter_rst_h1)

Then the template uses the filter like this:

  {{subtitle|rst_format_h1}}

Below is the patch - 4 new lines of code - to enable BuiltinLibrary:

---->8---->8---->8----
$ svn diff django/template
Index: django/template/__init__.py
===================================================================
--- django/template/__init__.py (revision 5572)
+++ django/template/__init__.py (working copy)
@@ -912,6 +912,11 @@
             return func
         return dec

+class BuiltinLibrary(Library):
+    def __init__(self, *args, **kwargs):
+        Library.__init__(self, *args, **kwargs)
+        builtins.append(self)
+
 def get_library(module_name):
     lib = libraries.get(module_name, None)
     if not lib:

---->8---->8---->8----

Here is a complete, standalone example program:

---->8---->8---->8----
"""Proof of concept for on-the-fly, standalone DJango filter code.

Problem: in some of my work I use the nifty DJango template code
  for documentation generation in standalone code - i.e. I generate
  documentation of some form without using any web app/infrastructure
  at all.

  DJango can works fine sans-web so long as you set it up correctly
  and you don't use custom filters or tags.

  Actually, thats not 100% true. You *can* use custom filters and tags,
  but it takes a bit of magic that I didn't think should be necessary.

  The challenge was to submit a patch to the DJango code, but to do
  that I need a small demo app that proves the new work..


Objective: Render a template, completely standalone, using custom filters
  and tags, in a "Django-compliant" way with minimal code changes to DJango.

  Specifically, this demo renders some restructured text using filters
  to generate underlines and header formatting.

Remember: the changes to DJango mustn't break any existing behavior!

A.E. June 2007
"""
import sys, re, os, os.path

try: import django
except ImportError, e:
        sys.stderr.write("DJango not installed\n")
        sys.exit(1)

template_content="""{{ title|rst_format_title:"=" }}

{{author|rst_format_author}}
{% rst_doc_date %}

{{subtitle|rst_format_h1}}

{{para}}
"""

def do_filter_demo():
        """Render a template from a string using our local filter.
        
        This will render something like:
        >>>
        ===============
         Filtered Demo
        ===============
        
        :Author: A. Roark
        :Date:   2007-06-30 21:45:40.205000
        
        Simple restructured text demo
        -----------------------------
        
        This uses builtin filters for formatting text
        <<<
"""
        
        # Render the template here - note that no special imports/code needed.
        t=Template(template_content)
        context=Context({
                'title':   'Filtered Demo',
                'author':   'A. Roark',
                'subtitle': 'Simple restructured text demo',
                'para':     'This uses builtin filters for formatting text',
        })
        out=t.render(context)
        print "\nDjango Custom Filter Demo:\n>>>\n%s\n<<<\n" % out


#
# --- Define some filters here ---
#

def filter_rst_h1(value, arg='-'):
        "Write a single underline under the text"
        line=arg * len(value)
        return "%s\n%s" % (value, line)

def filter_rst_title(value, arg='-'):
        "Add a line before and after the text"
        line=arg * (2+len(value))
        return "%s\n %s \n%s" % (line, value, line)

def filter_rst_author(value, arg=None):
        return ":Author: %s" %value

#
# --- A simple tag ---
#
def tag_rst_doc_date(parser, token):
        # A "real" tag should be much more than this -
        # I'm amazed this works as-is, but its ok for a demo.
        # For real details, see:
        #
http://www.djangoproject.com/documentation/templates_python/#writing-the-compilation-function
        import datetime
        return ":Date:   %s" % datetime.datetime.now()

#
# --- Main code ---
#
if __name__ == "__main__":

        # In a standalone app, do this first, before other imports
        from django.conf import settings
        settings.configure(
                # for debug:
                #   DEBUG=True, TEMPLATE_DEBUG=True,
                # for template files, something like...
                #   TEMPLATE_DIRS=(root_dir, os.path.join(root_dir, 'ref'))
                )

        from django.template import Template, Context, BuiltinLibrary
        
        # set up extra library of routines for later use...
        custom_library = BuiltinLibrary()
        custom_library.filter('rst_format_title',  filter_rst_title)
        custom_library.filter('rst_format_h1',     filter_rst_h1)
        custom_library.filter('rst_format_author', filter_rst_author)
        custom_library.tag(   'rst_doc_date',      tag_rst_doc_date)
        
        do_filter_demo()

---->8---->8---->8----

WDYT?

Andrew



--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to