Skip to content

Custom languages

Ross Morsali edited this page May 22, 2022 · 14 revisions

Custom languages are supported and can be defined in your build process by passing arguments to our plugin via your babel config.

Defining a custom lanaguage

A custom language doesn't have be a different language to the ones we provide, but also allows you add your own modifications, such as escaping functions, and variable names that are output.

This is an example of a custom language phpwp - essentailly - PHP for WordPress, which includes the WordPress escaping function esc_html() in the PHP output, otherwise, it is an exact copy of the php language supplied with this plugin:

const phpwp = {
  name: 'phpwp',
	replace: {
		format: `<?php echo esc_html( $data[ "||%1||" ] ); ?>`,
	},
	list: {
		open: `<?php foreach ( $data[ "||%1||" ] as $item ) { ?>`,
		close: `<?php } ?>`,
		formatObjectProperty: `<?php echo esc_html( $item[ "||%1||" ] ); ?>`,
		formatPrimitive: `<?php echo esc_html( $item ); ?>`,
	},
	control: {
		ifTruthy: {
			open: `<?php if ( $data[ "||%1||" ] ) { ?>`,
			close: '<?php } ?>',
		},
		ifFalsy: {
			open: `<?php if ( ! $data[ "||%1||" ] ) { ?>`,
			close: '<?php } ?>',
		},
		ifEqual: {
			open: `<?php if ( $data[ "||%1||" ] === ||%2|| ) { ?>`,
			close: '<?php } ?>',
		},
		ifNotEqual: {
			open: `<?php if ( $data[ "||%1||" ] !== ||%2|| ) { ?>`,
			close: '<?php } ?>',
		},
	}
};

To register and use this language, you have to specify in your babel config that the phpwp language will be used, and then supply it as a customLanguage:

plugins: [ 
	[ 'babel-plugin-jsx-template-vars', { language: 'phpwp', customLanguage: phpwp } ],
],

What's important here is that the language value matches the name property supplied to the object phpwp, which in this case is also phpwp.

Clone this wiki locally