Commits

Anonymous committed 64d2dfc

[svn] o added new asset_tag module, includes image_tag, stylesheet_link_tag and javascript_include_tag
moved from the javasript module
o made javascript_include_tag automatically append '.js' to includes when appropriate. The
other asset_tag functions do similar (e.g. image_tag defaults to '.png')

Comments (0)

Files changed (4)

tests/test_asset_tag.py

+from unittest import TestCase
+import unittest
+
+from webhelpers.rails.asset_tag import *
+
+class TestAssetTagHelper(TestCase):
+    def test_image_tag(self):
+        self.assertEqual('<img alt="Xml" src="/images/xml.png" />',
+                         image_tag('xml'))
+        self.assertEqual('<img alt="rss syndication" src="/images/rss.png" />',
+                        image_tag('rss', alt='rss syndication'))
+        self.assertEqual('<img alt="Gold" height="70" src="/images/gold.png" width="45" />',
+                         image_tag('gold', size='45x70'))
+        self.assertEqual('<img alt="Symbolize" height="70" src="/images/symbolize.png" width="45" />',
+                         image_tag('symbolize', size='45x70'))
+        self.assertEqual('<img alt="Pylons-Tower-Dark1" src="http://pylons.tgtg.org/powered/_img/pylons-tower-dark1.png" />',
+                         image_tag('http://pylons.tgtg.org/powered/_img/pylons-tower-dark1.png'))
+
+    def test_javascript_include_tag(self):
+        self.assertEqual("""<script src="/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/javascripts/scriptaculous.js" type="text/javascript"></script>""",
+                         javascript_include_tag(builtins=True))
+        self.assertEqual("""<script src="/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/other-javascripts/util.js" type="text/javascript"></script>""",
+                         javascript_include_tag('prototype', '/other-javascripts/util.js'))
+        self.assertEqual("""<script src="/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/javascripts/scriptaculous.js" type="text/javascript"></script>\n<script src="/javascripts/app.js" type="text/javascript"></script>\n<script src="/test/test.1.js" type="text/javascript"></script>""",
+                         javascript_include_tag('app', '/test/test.1.js', builtins=True))
+
+    def test_stylesheet_link_tag(self):
+        self.assertEqual('<link href="/stylesheets/style.css" media="screen" rel="Stylesheet" type="text/css" />',
+                         stylesheet_link_tag('style'))
+        self.assertEqual('<link href="/dir/file.css" media="all" rel="Stylesheet" type="text/css" />',
+                         stylesheet_link_tag('/dir/file', media='all'))
+        self.assertEqual('<link href="/stylesheets/dir/file.css" media="screen" rel="Stylesheet" type="text/css" />',
+                         stylesheet_link_tag('dir/file'))
+        self.assertEqual('<link href="/stylesheets/style.css" media="all" rel="Stylesheet" type="text/css" />',
+                         stylesheet_link_tag('style', media='all'))
+        self.assertEqual('<link href="/stylesheets/random.styles" media="screen" rel="Stylesheet" type="text/css" />\n<link href="/css/stylish.css" media="screen" rel="Stylesheet" type="text/css" />',
+                         stylesheet_link_tag('random.styles', '/css/stylish'))
+
+if __name__ == '__main__':
+    suite = [unittest.makeSuite(TestAssetTagHelper)]
+    for testsuite in suite:
+        unittest.TextTestRunner(verbosity=1).run(testsuite)

webhelpers/rails/__init__.py

 """Helper functions ported from Rails"""
+from asset_tag import *
 from urls import *
 from javascript import *
 from tags import *

webhelpers/rails/asset_tag.py

+"""
+Asset Tag Helpers
+
+Provides functionality for linking an HTML page together with other assets, such as
+javascripts, stylesheets, and feeds.
+"""
+import os
+from tags import *
+from routes import request_config
+
+# The absolute path of the WebHelpers javascripts directory
+javascript_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),
+                               'javascripts')
+
+# WebHelpers' built-in javascripts. Note: scriptaculous automatically includes all of its
+# supporting .js files
+javascript_builtins = ('prototype.js', 'scriptaculous.js')
+
+def image_tag(source, alt=None, size=None, **options):
+    """
+    Returns an image tag for the specified ``source``.
+
+    The source's URL path is prepended with '/images/', unless its full path is
+    specified. The source's URL path is ultimately prepended with the environment's
+    ``SCRIPT_NAME`` (the root path of the web application). A source with no filename
+    extension will be appended with the '.png' extension.
+    
+    ``alt``
+        The img's alt tag. Defaults to the source's filename, title cased.
+
+    ``size``
+        The img's size, specified in the format "XxY". "30x45" becomes
+        width="30", height="45". "x20" becomes height="20".
+        
+    Examples::
+
+        >>> image_tag('xml')
+        '<img alt="Xml" src="/images/xml.png" />'
+        >>> image_tag('rss', 'rss syndication')
+        '<img alt="rss syndication" src="/images/rss.png" />'    
+    """
+    options['src'] = compute_public_path(source, 'images', 'png')
+
+    if not alt:
+        alt = os.path.splitext(os.path.basename(source))[0].title()
+    options['alt'] = alt
+    
+    if size:
+        width, height = size.split('x')
+        if width:
+            options['width'] = width
+        if height:
+            options['height'] = height
+        
+    return tag('img', **options)
+
+def javascript_include_tag(*sources, **options):
+    """
+    Returns script include tags for the specified javascript ``sources``.
+
+    Each source's URL path is prepended with '/javascripts/' unless their full path is
+    specified. Each source's URL path is ultimately prepended with the environment's
+    ``SCRIPT_NAME`` (the root path of the web application). Sources with no filename
+    extensions will be appended with the '.js' extension.
+
+    Optionally includes (prepended) WebHelpers' built-in javascripts when passed the
+    ``builtins=True`` keyword argument.
+
+    Examples::
+    
+        >>> print javascript_include_tag(builtins=True)
+        <script src="/javascripts/prototype.js" type="text/javascript"></script>
+        <script src="/javascripts/scriptaculous.js" type="text/javascript"></script>
+
+        >>> print javascript_include_tag('prototype', '/other-javascripts/util.js')
+        <script src="/javascripts/prototype.js" type="text/javascript"></script>
+        <script src="/other-javascripts/util.js" type="text/javascript"></script>
+
+        >>> print javascript_include_tag('app', '/test/test.1.js', builtins=True)
+        <script src="/javascripts/prototype.js" type="text/javascript"></script>
+        <script src="/javascripts/scriptaculous.js" type="text/javascript"></script>
+        <script src="/javascripts/app.js" type="text/javascript"></script>
+        <script src="/test/test.1.js" type="text/javascript"></script>
+    """
+    if options.get('builtins'):
+        sources = javascript_builtins + sources
+        
+    tags = [content_tag('script', None,
+                        **dict(type='text/javascript',
+                               src=compute_public_path(source, 'javascripts', 'js'))) \
+            for source in sources]
+    return '\n'.join(tags)
+
+def stylesheet_link_tag(*sources, **options):
+    """
+    Returns CSS link tags for the specified stylesheet ``sources``.
+
+    Each source's URL path is prepended with '/stylesheets/' unless their full path is
+    specified. Each source's URL path is ultimately prepended with the environment's
+    ``SCRIPT_NAME`` (the root path of the web application). Sources with no filename
+    extension will be appended with the '.css' extension.
+    
+    Examples::
+
+        >>> stylesheet_link_tag('style')
+        '<link href="/stylesheets/style.css" media="screen" rel="Stylesheet" type="text/css" />'
+        >>> stylesheet_link_tag('/dir/file', media='all')
+        '<link href="/dir/file.css" media="all" rel="Stylesheet" type="text/css" />'
+    """
+    tag_options = dict(rel='Stylesheet', type='text/css', media='screen')
+    tag_options.update(options)
+    tag_options.pop('href', None)
+
+    tags = [tag('link', **dict(href=compute_public_path(source, 'stylesheets', 'css'),
+                               **tag_options)) for source in sources]
+    return '\n'.join(tags)
+    
+def compute_public_path(source, root_path, ext=None):
+    """
+    Format the specified source for publishing, via the public directory.
+    """
+    # Prefix apps deployed under any SCRIPT_NAME path
+    script_name = get_script_name()
+    if ext is not None and not os.path.splitext(os.path.basename(source))[1]:
+        source = '%s.%s' % (source, ext)
+    if source.startswith('/') or source.startswith('http://'):
+        source = '%s%s' % (script_name, source)
+    else:
+        source = '%s/%s/%s' % (script_name, root_path, source)
+    return source
+
+def get_script_name():
+    """
+    Determine the current web application's ``SCRIPT_NAME``.
+    """
+    script_name = ''
+    config = request_config()
+    if hasattr(config, 'environ'):
+        script_name = config.environ.get('SCRIPT_NAME', '')
+    return script_name
+
+__all__ = ['javascript_path', 'javascript_builtins', 'image_tag', 'javascript_include_tag',
+           'stylesheet_link_tag']

webhelpers/rails/javascript.py

 * For information on using Ajax, see `Prototype Helpers <module-railshelpers.helpers.prototype.html>`_.
 * For information on using controls and visual effects, see `Scriptaculous Helpers <module-railshelpers.helpers.scriptaculous.html>`_.
 """
-import os
 import re
 from tags import *
-from routes import request_config
-
-# The absolute path of the WebHelpers javascripts directory
-javascript_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),
-                               'javascripts')
-
-# WebHelpers' built-in javascripts. Note: scriptaculous automatically includes all of its
-# supporting .js files
-javascript_builtins = ('prototype.js', 'scriptaculous.js')
 
 def link_to_function(name, function, **html_options):
     """
     """
     return content_tag("script", javascript_cdata_section(content), type="text/javascript")
 
-def javascript_include_tag(*sources, **options):
-    """
-    Returns script include tags for the specified javascript ``sources``.
-
-    Each source's URL path is prepended with '/javascripts/' unless their full path is
-    specified. Each source's URL path is ultimately prepended with the environment's
-    ``SCRIPT_NAME`` (the root path of the web application).
-
-    Optionally includes (prepended) WebHelpers' built-in javascripts when passed the
-    ``builtins=True`` keyword argument.
-
-    Examples::
-    
-        >>> print javascript_include_tag(builtins=True)
-        <script src="/javascripts/prototype.js" type="text/javascript"></script>
-        <script src="/javascripts/scriptaculous.js" type="text/javascript"></script>
-
-        >>> print javascript_include_tag('prototype.js', '/other-javascripts/util.js')
-        <script src="/javascripts/prototype.js" type="text/javascript"></script>
-        <script src="/other-javascripts/util.js" type="text/javascript"></script>
-
-        >>> print javascript_include_tag('app.js', '/test/test.js', builtins=True)
-        <script src="/javascripts/prototype.js" type="text/javascript"></script>
-        <script src="/javascripts/scriptaculous.js" type="text/javascript"></script>
-        <script src="/javascripts/app.js" type="text/javascript"></script>
-        <script src="/test/test.js" type="text/javascript"></script>
-    """
-    if options.get('builtins'):
-        sources = javascript_builtins + sources
-        
-    # Prefix apps deployed under any SCRIPT_NAME path
-    script_name = ''
-    config = request_config()
-    if hasattr(config, 'environ'):
-        script_name = config.environ.get('SCRIPT_NAME', '')
-
-    include_tags = []
-    format_source = lambda s: s.startswith('/') and '%s%s' % (script_name, s) or \
-        '%s/javascripts/%s' % (script_name, s)
-    [include_tags.append(content_tag('script', None, **dict(type='text/javascript',
-                                                            src=format_source(source)))) \
-     for source in sources]
-    return '\n'.join(include_tags)
-
 def javascript_cdata_section(content):
     return "\n//%s\n" % cdata_section("\n%s\n//" % content)
 
         jsoption = "'%s'" % option
     return jsoption
 
-__all__ = ['javascript_path', 'javascript_builtins', 'link_to_function', 'button_to_function',
-           'escape_javascript', 'javascript_tag', 'javascript_include_tag']
+__all__ = ['link_to_function', 'button_to_function', 'escape_javascript', 'javascript_tag']
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.