pythonplonezopetemplate-talzpt

How to set TAL condition to check the file type and accordingly render the template in Plone 4.1


How to use the tal condition to check the file type and render the template in Plone 4.1

My file preview template rendering depends upon the file extension. If file extension is 'pdf', I wish to use something like this:(just started working with TAL, TALES, METAL)

<tal:define="file_nm global string:${here/absolute_url}"
<tal:condition="file_nm.slice[-3:] = 'pdf'">

    <embed width="100%" height="100%" name="plug-in" tal:attributes="src string:${here/absolute_url}#" 
         draggable="false" onselectstart="false"  />

else use :(for files other than 'pdf')

<IFRAME src="http://www.xyz.com" 
            tal:attributes="src string:${here/absolute_url}/rfpreview"
            ondragstart="false" onselectstart="false"
            width="100%" height="400" scrolling="auto" frameborder="0"></IFRAME>

Can someone guide me on the complete custom code snippet for custom view :atreal.richfile.preview.interfaces.ipreview-atreal.richfile.preview.viewlet


Solution

  • TAL statements are attributes on existing tags. You can introduce dummy elements with the tal: namespace prefix, but the statements like define and condition need to expressed as attributes still.

    Also, the default TALES expression type is path expressions, but you want to use python expressions. That's fine, but you need to specify them as such with the python: prefix.

    Last but not least, don't use global unless you absolutely have to, which is really rarely. Defined names live in the scope of the XML element they are defined on, and don't need to live on outside of these.

    Here is how I'd express the logic:

    <tal:block define="ispdf python:here.absolute_url().endswith('.pdf')">
    
        <embed width="100%" height="100%" name="plug-in" 
             tal:condition="ispdf"
             tal:attributes="src string:${here/absolute_url}#" 
             draggable="false" onselectstart="false"  />
    
        <iframe src="http://www.xyz.com" 
             tal:condition="not:ispdf"
             tal:attributes="src string:${here/absolute_url}/rfpreview"
             ondragstart="false" onselectstart="false"
             width="100%" height="400" scrolling="auto" frameborder="0"></iframe>
    
    </tal:block>
    

    This introduces a new <tal:block> element to define the ispdf boolean variable, determined by a python expression. Then the two variants are switched on or off by the tal:condition attributes on each element based on that value being True or False.