フリーマーカーでテンプレートのパスをどのように設定しますか?
Freemarkerでは、freemarker.template.Configurationオブジェクトを設定してテンプレートパスを指定することができます。以下は一般的な設定方法の例です。
- 構成 (Kousei)
import freemarker.template.Configuration;
Configuration cfg = new Configuration(Configuration.VERSION_2_3_31);
- テンプレートのパスを設定します。
// 设置模板文件夹路径
cfg.setDirectoryForTemplateLoading(new File("path/to/templates"));
// 或者,设置类路径下的模板文件夹路径
cfg.setClassForTemplateLoading(getClass(), "/templates");
- テンプレートファイルを取得する。
Template template = cfg.getTemplate("templateName.ftl");
上記のコードでは、path/to/templatesはテンプレートフォルダの絶対パスであり、また/templatesはクラスパスの下の相対パスです。
注意:テンプレートのパスを設定する際には、テンプレートファイルの場所とアクセス権限に注意してください。