Skip to main content

Turn Your Own Code into a Template

Start with code that already works, and turn it into a template one step at a time.

Template creation workflow​

  1. Copy your working code into .CodeBaker/YourTemplate/, keeping its relative folder structure, measured from the folder you will later generate into
  2. Create the main config file, codebaker.config.json5, in the template folder: give the template a name, declare its variables, define custom placeholders and more, as described in the Configuration Reference
  3. Replace values with placeholders: "User" → ___modelName___
  4. Add conditional logic (optional): //CodeBaker: {% if needsTests %}
  5. Generate, review the diff, and refine
Limit where a template can be started

A template keeps the relative structure of the folder you generate into, so it is worth limiting it to start only from the folders where that structure is correct. This keeps the generated files in the right place in your project. Use the paths option in codebaker.config.json5: the template is then offered only when you right-click a matching folder, for example paths: { include: ["app/Models"] }.

See Configuration Reference: paths for all the options and the pattern syntax.

Start with simple replacements. Add logic and advanced mapping only when the template needs them.

Example: from working code to a template​

// Step 1: Your existing code
class User extends Model
{
protected $table = 'users';
public $timestamps = true;
}
// Step 2: .CodeBaker/YourTemplate/codebaker.config.json5
{
name: "Model",

// The placeholder style used in this template.
// Nothing but Pebble's {{ name }} is built in, so list the style you want,
// for example ___VAR___, or define your own.
placeholders: ["___VAR___"],

vars: {
ModelName: "User",
tableName: "users",
hasTimestamps: "true",
},
}
// Step 3: Replace values with placeholders
class ___ModelName___ extends Model
{
protected $table = '___tableName___';
public $timestamps = true;
}
// Step 4: Add logic where the output should vary
class ___ModelName___ extends Model
{
protected $table = '___tableName___';
//CodeBaker: {% if hasTimestamps %}
public $timestamps = true;
//CodeBaker: {% else %}
public $timestamps = false;
//CodeBaker: {% endif %}
}
  • Duplicate property declaration: $timestamps

Step 5: generate, review the diff, adjust the template, and repeat.

Two details of the Step 4 template:

  • hasTimestamps is a vars entry like any other, so the user types true or false in the dialog. The typed text true/false is turned into a real boolean, which is what makes {% if hasTimestamps %} work.
  • Your IDE reads both branches of the condition, so it marks the second $timestamps as a duplicate declaration. This appears only in the template: the generated code contains just one of the two properties. We keep it simple here for now, but Keeping the Template Valid for Your IDE shows how to avoid it.

Next steps​