Home > Articles > Web Development

Code Concepts 101: Using Logic in Zope's DTML

📄 Contents

  1. More DTML Options: Process Flow Control
  2. DTML Expressions
  3. About This Article
  • Print
  • + Share This
Steve Spicklemire, Kevin Friedly, Jerry Spicklemire, and Kim Brand, authors of Zope: Web Application Development and Content Management, show you how to use the Document Template Markup Language (DTML) to create simple "wrapper" methods that perform basic logic in DTML to decide how to display their wrapped content.
Like this article? We recommend

DTML can be confusing until you learn some of the basic ideas and encounter the "rough spots." This article explains some strategies that you can use to apply DTML's built-in flow control and logical decision-making capabilities. The objective is to create dynamic web pages that know what to display in different circumstances. To begin, create a DTML method object with an ID of standard_dtml_wrapper and a title of Site Wrapper Method, as shown in Listing 1.

Listing 1: A "Wrapper" DTML Method

01 <HTML>
02 <HEAD>
03  <TITLE><dtml-var title></TITLE>
04 </HEAD>
05 <BODY>
06  <dtml-var banner>
07  <dtml-var expr="_[page_body]" fmt=structured-text>
08 </BODY>
09 </HTML>

Notice line 07, which says fmt=structured-text. That is the notation that activates the filter to convert from structured text to HTML.

You will refine the wrapper as the exercise progresses.

Next create an Image object called banner_logo that contains the image that you'd like to use as a banner for your site. You won't see a reference to the logo image in the wrapper because it is really "part of" the banner. Create your banner object as a DTML method with the ID of banner and the title Site Banner. This time, replace the default text with this line:

<dtml-var banner_logo><h1><dtml-var title></h1>

You might be surprised that the reference to banner_logo doesn't specify the image size, or even the fact that the element is an image. Zope handles all of that for you because you created the object as an image type. In some cases, you might need to specify a width and height if you want to scale the image differently from its original dimensions. Notice that the banner text is simply the title of the MyHome.html object, which has been rendered as a heading.

More DTML Options: Process Flow Control

A value stored as a variable can be created at one point in a process and referred to at some later point. This is truly the most basic aspect of computer programming, but it might be new to some readers who have been working primarily with conventional HTML and graphics. Things really get interesting when the process itself relies on the stored value to determine which one of a set of possible actions to carry out. This is a type of automation being put to work in the creation of dynamic web pages.

Branching: A Fork in the Decision Tree

Consider the variable page_body, which serves to identify the unique page content of this example. The standard_dtml_wrapper is written so that it assumes that this variable has been assigned. The example is simple and easy to understand, which suited your needs, but it is not comprehensive. What would happen if a call were made to the wrapper method, but the variable didn't yet exist? You will see the Zope error screen often enough, so start applying a bit of prevention right now. Select standard_dtml_wrapper from the site_folder.

You need to add a logical "branch," a decision point where Zope can check to see if the variable has been set. That way, the process can continue normally when all goes well, but it can carry out default behavior in case of an omission.

The new DTML syntax that you will use is called <dtml-if>, and it can be inserted into the existing dtml method object standard_dtml_wrapper, as seen in Listing 2.

Listing 2: Adding a Branch to the Wrapper

01 <html>
02 <head>
03  <title><dtml-var title_or_id></title>
04 <head>
05 <body>
06  <dtml-var banner>
07  <dtml-if page_body>
08  <dtml-var "_[page_body]" fmt=structured-text>
09  <dtml-else>
10  <dtml-var default_page>
11  </dtml-if>
12 </body>
13 </html>

The tag at line 07, <dtml-if page_body>, simply checks to see that a variable with the name page_body exists. The <dtml-if> asks ZPublisher to confirm whether calling an object named page_body results in a nonempty value, which, in code lingo, is interpreted as true. If so, the next line carries on as before, but the <dtml-else> line allows for the possibility that the result was false, such as when the variable does not exist. If that happens, the line after <dtml-else> will be carried out.

Of course, now you have to create a default_page object that will always be available for such contingencies. In this case, the new object could be a document that displays a line of text saying something like, "The page you requested is not available at this time." At least that would be more polite and considerate than an alarming "ERROR!" message. Go ahead and create a DTML document with an ID of default_page and a title of Default Error Massage, and replace the template text with the message of your choice. You can improve it as you gain expertise, but at least it will work well enough for now.

Looping: Doing It Until It's Done

Another basic flow-control construct is known as a loop. Loops enable iteration over a set of elements so that each one is processed in turn. For example, the cases that were allowed for in the previous code allow only two possible objects for insertion into a page after the banner. Another approach might be to create a list of possible object names and test for each one from the most common to the least. While cumbersome, this idea could come in handy when you have a set of possible conditions that is neither too short nor too long in number. If you need a name to help you remember this sort of judgment call, which arises frequently in the programming field, you could call it the "Goldilocks Principle" (as in "too hot, too cold, just right"). The choices that programmers make are less often the consistent application of clear-cut "laws" as much as "guesstimates" that are arrived at through experience and personal preference.

The most-used loop construct in DTML is <dtml-in sequence_name>, which applies a template or process to each item that is "in" a set if items. You will be using <dtml-in> loops frequently, especially when working with databases and queries.

Nested Branches

You might be thinking of any number of other ways to handle this. So, take a look at one more variation of this method—this time with two branches, one "nested" inside another—with the text in Listing 3.

Listing 3: Choosing One of Three Options

01 <html>
02 <head>
03  <title><dtml-var title_or_id></title>
04 <head>
05 <body>
06  <dtml-var banner>
07  <dtml-if page_body>
08   <dtml-if "page_body[-4:]=='.stx'">
09   <dtml-var "_[page_body]" fmt=structured-text>
10   <dtml-else>
11   <dtml-var "_[page_body]">
12   </dtml-if>
13  <dtml-else>
14   <dtml-var default_page>
15  </dtml-if>
16  </body>
17 </html>

The new case that you are handling in Listing 3 covers the possibility that the page_body variable names an object that isn't formatted as structured_text. An example of this case is an existing HTML page that has been adapted so that it can be wrapped and used on this new site. Line 08 in this version, <dtml-if "page_body[-4:]==.stx'">, tests whether the value stored as page_body has the string ".stx" as the last four characters. The brackets, -4, and colon are an example of the "slice syntax" used in Python.

The number and colon in this example mean, "all the characters in this string, from the fourth from the last, to the end."

Knowing Python Helps You Understand Zope

Many articles about Zope, beginners tutorials, and helpful Zope users will assure you that mastery of Python isn't required to use Zope effectively. However, plenty of enthusiastic Python coders got their first glimpse of Python when they tried Zope. No one will dispute the fact that the more Python you know, the easier it will be to get the most out of Zope.

So, don't let the fact that you can indeed use Zope without really understanding Python keep you from adding this powerful and popular language to your toolkit. Especially if you are new to programming, look no further than Python. Python is famous for both its approachability and its practical usefulness.

To start your Python explorations, see any of the excellent tutorials listed at these links:

http://www.python.org/doc/Intros.html

http://www.ibiblio.org/obp/thinkCSpy/

http://www.honors.montana.edu/~jjc/easytut/easytut/

Zope is nearly all Python code—and not by accident. When the Zope folks chose Python, they did so because they knew that the benefits of a language steeped in object-oriented concepts with unmatched clarity and ease of use would empower Zope to support challenging and sophisticated web development projects. Python's capability to run on a wide range of hardware and software platforms is another essential ingredient. The web is only beginning to demonstrate the need to accommodate diverse and unanticipated uses, from cell phones and handhelds to smart cars and global satellite systems. Even if your projects don't demand absolute state-of-the-art technology, it can be very comforting to know that "it's in there."

A bit of explanation is in order regarding the specifics of the references to the variable page_body at different points in the standard_dtml_wrapper in Listing 3. Sometimes it's in quotes, and sometimes not. Sometimes it's in brackets but is not quoted. Looking back at the original instance, recall that the variable is assigned with the name of the object enclosed in single quotes and then is double-quoted as well. This all looks mysterious, and it certainly takes some of getting used to, but hang in there. We'll go through each case—and then show you how to totally bypass the worst of it altogether with a wonderful new feature called Python Scripts that appeared in Zope as of Version 2.3.

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020