001    // Copyright 2005 The Apache Software Foundation
002    //
003    // Licensed under the Apache License, Version 2.0 (the "License");
004    // you may not use this file except in compliance with the License.
005    // You may obtain a copy of the License at
006    //
007    //     http://www.apache.org/licenses/LICENSE-2.0
008    //
009    // Unless required by applicable law or agreed to in writing, software
010    // distributed under the License is distributed on an "AS IS" BASIS,
011    // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
012    // See the License for the specific language governing permissions and
013    // limitations under the License.
014    
015    package org.apache.tapestry.services.impl;
016    
017    import org.apache.tapestry.IMarkupWriter;
018    import org.apache.tapestry.IPage;
019    import org.apache.tapestry.IRender;
020    import org.apache.tapestry.IRequestCycle;
021    
022    /**
023     * Contains code needed to render the <base> tag for pages. The <base> tag ensures that
024     * the base URL for the rendered page matches the location of the page template in the servlet
025     * context, so that relative URLs to static assets (images, stylesheets, etc.) will be processed
026     * correctly. This is important starting with release 4.0, where HTML templates are no longer
027     * restricted to the servlet root.
028     * <p>
029     * Note that pages outside of the application namespace (provided by the framework itself, or in a
030     * library) are "virtually located" in the application root.
031     * 
032     * @author Howard M. Lewis Ship
033     * @since 4.0
034     */
035    public class BaseTagWriter implements IRender
036    {
037    
038        public void render(IMarkupWriter writer, IRequestCycle cycle)
039        {
040            IPage page = cycle.getPage();
041    
042            StringBuffer sb = new StringBuffer();
043            sb.append("/");
044    
045            if (page.getNamespace().getId() == null)
046            {
047                String name = page.getPageName();
048                int slashx = name.lastIndexOf('/');
049    
050                // Include the directory and trailing slash.
051                if (slashx > 0)
052                    sb.append(name.substring(0, slashx + 1));
053            }
054    
055            String url = cycle.getAbsoluteURL(sb.toString());
056    
057            writer.beginEmpty("base");
058            writer.attribute("href", url);
059            writer.printRaw("<!--[if IE]></base><![endif]-->");
060    
061            writer.println();
062        }
063    
064    }