DEV Community

Cover image for Enhance PhpStorm File Templates with Velocity 🧪
Honza Černý
Honza Černý

Posted on

3

Enhance PhpStorm File Templates with Velocity 🧪

Using PhpStorm’s File Templates makes it easier to create linked files in frameworks like presenters/controlers and their templates. By setting up custom templates, you can quickly generate these files with the right structure. Using Velocity variables like ${NAME} and ${DIR_PATH} can helps automatically create file names and paths, reducing mistakes.

🜁

In my case, I use the Nette Framework. There is a Presenter (HomepagePresenter.php) connected with a Template (Homepage.default.latte) in a Module (Admin):

/app/modules/Admin/Homepage/templates/Homepage.default
/app/modules/Admin/Homepage/HomepagePresenter.php
Enter fullscreen mode Exit fullscreen mode

I want a File Template that asks for just one name and prepares everything else 💥

Wizard dialog with input field

  1. Go to: Settings → Editor → File and Code Templates
  2. Create a new Template and use the variable ${NAME}

🜛

use variables in both the code and the path

code example with variable

For the second file, use “Create Child Template File”🜔

icon of Create Child Template File

example of template file with velocity variable

We can create another variable named ${MODULE} for setting the namespace like this:

namespace App\\${MODULE}Module\Presenters;
Enter fullscreen mode Exit fullscreen mode

But ...

🜇 / 🜂 = 🜸 + 🜍🜞

when you study a little bit of Velocity templates and the variables that PhpStorm provides, you can combine them to automate some processes.

In Velocity, #set is used for variable settings, and PhpStorm suggests the variable ${DIR_PATH} – the path to the directory of the new file (relative to the project root).

So we can start our Presenter template with this power 🜣 and use new variable ${moduleName} in the code.

#set($dirPath = ${DIR_PATH})
#set($parentDirPath = $dirPath.substring(0, $dirPath.lastIndexOf("/")))
#set($moduleName = $parentDirPath.substring($parentDirPath.lastIndexOf("/") + 1))
<?php

namespace App\\${moduleName}Module\Presenters;
Enter fullscreen mode Exit fullscreen mode

And that’s it. Just a few lines of Velocity and more automated creation of File Templates is done. There is no magic, just digital alchemy 👨‍🔬⚗️

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More