Attention

This document was written for an unsupported version of Plone, Plone 2.1.x, and was last updated 335 days ago.

For more information, see the version support policy.

To learn how to upgrade to the current version of Plone, read the upgrade manual.

Using the transforms

by Martin Aspeli last modified Jun 23, 2011 01:38 PM
Using the transforms via the PortalTransforms API, and automatically in Archetypes fields.

Now that the transforms are registered, you can use 'portal_transforms' to convert between types. If you took the time to read the test cases in 'tests/test_transforms.py', you will already have seen how this works.

It is possible to invoke transforms by name:

text = 'Make this a link: http://plone.org.'

portal_transforms = getToolByName(self, 'portal_transforms')
data = portal_transforms.convert('web_intelligent_plain_text_to_html', text)
html = data.getData()

However, in most cases, you will be more interested in converting between two MIME types:

text = 'Make this a link: http://plone.org.'

portal_transforms = getToolByName(self, 'portal_transforms')
data = portal_transforms.convertTo('text/html', text,
                                        mimetype='text/-x-web-intelligent')
html = data.getData()

Here, 'text' contains some text, and we tell 'convertTo()' that this should be treated as 'text/x-web-intelligent'. We then ask it to convert this text to 'text/html', and fetch the actual HTML from the 'idatastream' returned via the 'getData()' method.

The nice thing about 'PortalTransforms' is that it completely isolates you from the underlying transform code. For example, you can now create an Archetypes schema containing:

TextField('text',
    widget=TextAreaWidget(
        label="Text",
        description="Enter some text",
    ),
    searchable=True,
    default_content_type="text/x-web-intelligent",
    allowable_content_types=('text/x-web-intelligent',),
    default_output_type="text/html"
),

If edited through the web, Archetypes will ensure that the content is saved with mimetype 'text/x-web-intelligent', and is output as 'text/html'. If you are calling the mutator directly, you need to specify the MIME type manually:

instance.setText('Go to http://plone.org',
                    mimetype='text/x-web-intelligent')

When this is displayed or you call the accessor, 'portal_transforms' will look for a way to convert 'text/x-web-intelligent' to 'text/html', and will invoke the 'web_intelligent_plain_text_to_html' transform as long as 'intelligenttext' is installed in 'portal_quickinstaller':

html = instance.getText()

You can also be explicit about which MIME type you'd like back:

text = instance.getText(mimetype = 'text/x-web-intelligent')

For more details, see 'PortalTransforms/interfaces.py'.


Contribute

Something wrong or out of date? Anybody can edit or create a new article in the knowledge base. Simply create an account on this site, log in, and click the Edit button to contribute.