001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.wicket.velocity; 018 019import java.util.Map; 020 021import org.apache.velocity.runtime.resource.loader.FileResourceLoader; 022import org.apache.wicket.Component; 023import org.apache.wicket.markup.head.IHeaderResponse; 024import org.apache.wicket.markup.head.JavaScriptHeaderItem; 025import org.apache.wicket.model.IModel; 026import org.apache.wicket.util.lang.Packages; 027 028/** 029 * A derivation of VelocityContributor that uses 030 * {@link org.apache.wicket.markup.head.IHeaderResponse#render(org.apache.wicket.markup.head.HeaderItem)} 031 */ 032public class VelocityJavaScriptContributor extends VelocityContributor 033{ 034 private static final long serialVersionUID = 1L; 035 036 private final String id; 037 038 /** 039 * Use this constructor if you have configured Velocity to use a ClasspathResourceLoader. The 040 * templatePath will then be relative to the package for clazz 041 * 042 * @param clazz 043 * @param templatePath 044 * @param model 045 * @param id 046 */ 047 public VelocityJavaScriptContributor(final Class<?> clazz, final String templatePath, 048 final IModel<? extends Map<String, Object>> model, final String id) 049 { 050 super(Packages.absolutePath(clazz, templatePath), model); 051 this.id = id; 052 } 053 054 /** 055 * Use this constructor when Velocity is configured with the {@link FileResourceLoader}. 056 * templatePath with then be relative to the loader path configured in velocity.properties 057 * 058 * @param templatePath 059 * @param model 060 * @param id 061 */ 062 public VelocityJavaScriptContributor(final String templatePath, 063 final IModel<? extends Map<String, Object>> model, final String id) 064 { 065 super(templatePath, model); 066 this.id = id; 067 } 068 069 /** 070 * {@inheritDoc} 071 */ 072 @Override 073 public void renderHead(final Component component, final IHeaderResponse response) 074 { 075 CharSequence s = evaluate(); 076 if (s != null) 077 { 078 response.render(JavaScriptHeaderItem.forScript(s, id)); 079 } 080 } 081}