[Zope-dev] Patch: Add versatile "tag" method to Image

bruce@perens.com bruce@perens.com
13 Jul 1999 19:15:39 -0000


The Image class has a str() method that outputs an <IMG ...> tag with an
absolute URL, and with the height, width, and alternate text set for you.
This is a very efficient way to embed images in your documents, because the
page renders better when the height and width of the image are given and you
don't have to hard-code them into your document, and the absolute URL uses the
web browser's cache efficiently.

However, I found this method constraining in that I could not add attributes
such as "BORDER=0" to the tag. This patch adds a more versatile tag() method
to Image. Arguments to the tag() method can be any of the usual IMG
attributes. Defaults are provided for height and width (again, set from
the image file) and  For example:

<!--#var "MyImage.tag(border=0, align='CENTER', hspace=2, vspace=2)"-->

... will result in the image being rendered with the given attributes.

Can we get something like this included in the main Zope thread?

	Thanks

	Bruce Perens

--- Zope.old/lib/python/OFS/Image.py	Mon May 24 20:49:12 1999
+++ Zope-2.0.0a3-src/lib/python/OFS/Image.py	Tue Jul 13 18:52:51 1999
@@ -133,7 +133,7 @@
         ('View management screens', ('manage','manage_main',
                                      'manage_uploadForm',)),
         ('Change Images and Files', ('manage_edit','manage_upload','PUT')),
-        ('View', ('index_html','view_image_or_file','getSize','getContentType',
+        ('View', ('index_html','tag','view_image_or_file','getSize','getContentType',
                   '')),
         ('FTP access', ('manage_FTPstat','manage_FTPget','manage_FTPlist')),
         ('Delete objects', ('DELETE',)),
@@ -363,7 +363,35 @@
             self.absolute_url(), width, height, self.title_or_id()
             )
 
+    def tag(self, height=None, width=None, alt=None, **args):
+        """
+	Generate an HTML IMG tag for this image, with customization.
+	Arguments to self.tag() can be any valid attributes of an IMG tag.
+	'src' will always be an absolute pathname, to prevent redundant
+	downloading of images. Defaults are applied intelligently for
+	'height', 'width', and 'alt'.
+	"""
+	if not alt:
+	    alt=self.title_or_id()
+
+	string='<img src="%s" alt="%s"' % (self.absolute_url(), alt)
+
+	if not height:
+		height = self.height
+	if height:
+		string = "%s height=%s" % (string, height)
+	
+	if not width:
+		width = self.width
+	if width:
+		string = "%s width=%s" % (string, width)
+
+	for key in args.keys():
+	    value = args.get(key)
+	    string = "%s %s=%s" % (string, key, value)
 
+	return string + '>'
+		
 
 def cookId(id, title, file):
     if not id and hasattr(file,'filename'):