Ticket #7775 (new enhancement)
Opened 2 months ago
Method to add script tag with in-file javascript code
| Reported by: | martin@… | Owned by: | |
|---|---|---|---|
| Priority: | normal | Milestone: | |
| Component: | web frontend | Version: | none |
| Severity: | normal | Keywords: | |
| Cc: |
Description
While it is possible to add script tags for external javascript file using the add_script function in trac.web.chrome, it isn't possible to add script tags with in-file javascript code content.
While using only external javascript files is a good web design approach, some plug-ins might need to add small dynamic generated javascript code into the generated XHTML, e.g. to set variables which value depends on trac.ini settings or external sources. I had this problem recently with the GoogleMapMacro.
Because script tags shoudn't refer to an external file and have code content, I would like to suggest a new python method and template tag:
-
trac/templates/layout.html
diff -Naur Trac-0.11.1-py2.5.egg/trac/templates/layout.html Trac-0.11.1-py2.5.egg.new/trac/templates/layout.html
old new 22 22 </py:if> 23 23 <script py:for="script in chrome.scripts" 24 24 type="${script.type}" src="${script.href}"></script> 25 <script py:for="script in chrome.scriptscontent" type="${script.type}"> 26 /*<![CDATA[*/ 27 ${script.content} 28 /*]]>*/ 29 </script> 25 30 ${Markup('<!--[if lt IE 7]>')} 26 31 <script type="text/javascript" src="${chrome.htdocs_location}js/ie_pre7_hacks.js"></script> 27 32 ${Markup('<![endif]-->')} -
Trac-0.11.1-py2.5.egg
diff -Naur Trac-0.11.1-py2.5.egg/trac/web/chrome.py Trac-0.11.1-py2.5.egg.new/trac/web/chrome.py
old new 106 106 req.chrome.setdefault('scripts', []).append(script) 107 107 scriptset.add(filename) 108 108 109 def add_script_content(req, content, mimetype='text/javascript'): 110 """Add in-file javascript code to the template. 111 112 """ 113 import hashlib 114 m = hashlib.md5() 115 m.update(content) 116 digest = m.hexdigest() 117 118 scriptcontentset = req.chrome.setdefault('scriptcontentset', set()) 119 if digest in scriptcontentset: 120 return False # Already added that code 121 122 scriptcontent = {'content': content, 'type': mimetype} 123 124 req.chrome.setdefault('scriptscontent', []).append(scriptcontent) 125 scriptcontentset.add(digest) 126 109 127 def add_javascript(req, filename): 110 128 """Deprecated: use `add_script()` instead.""" 111 129 add_script(req, filename, mimetype='text/javascript')


