Search code examples
intellij-idea

Capitalize ${NAME} in File and Code Templates


Problem

In Preferences -> Editor -> File and Code Templates I have a template for React with:

import React from 'react';

class ${NAME} extends React.Component {

  render() {
    return (
      <div>
        #[[$END$]]#
      </div>
    );
  }
} 

export default ${NAME};

Is there a way to capitalize the ${NAME}?

We have a convention of naming our files starting with a lowercase but in React components are meant to be capitalized.

Additional Information

I'm aware of the IntelliJ's ability to refactor and that you can use a Live Templates to accomplish this but I would like to remove this extra step :).

This is possible in Live Templates where you can define and reference a expression like capitalize(fileNameWithoutExtension()) but I couldn't find anywhere to define expressions in File and Code Templates.


Solution

  • So after doing some research I came up with this:

    import React from 'react';
    
    #set($capitalizedFilename = $NAME.substring(0,1).toUpperCase() + $NAME.substring(1))
    class $capitalizedFilename extends React.Component {
      
      render() {
        return (
          <div>
            #[[$END$]]#
          </div>
        );
      }
    } 
    
    export default $capitalizedFilename;