Skip to main content

Hygen create template for blog

· 3 min read

This blog post shows how to create a hygen template for blog.

This work is inspired by zxuqian.cn and Hygen.

Hygen is a code generator that helps you scaffold code, files, and anything else you can describe with a template. It is a great tool to automate repetitive tasks and save time.

If you want to create a hygen template for blog, you can follow these steps:

Step 1: Install Hygen

Integrate Hygen into your project by running the following command:

yarn add hygen

Step 2: Create a Hygen Template

Create a folder named _templates in the root directory of your project. Inside the _templates folder, create a folder named blog to store the hygen template for blog.

Then create a folder named new inside the blog folder. This folder will contain the template files for creating a new blog post and a prompt file to collect user input.

_templates/blog
├── new
├── index.ejs
└── prompt.js

In the index.ejs file, you can define the structure of the blog post template using EJS syntax. For example:

---
to: blog/<%= date %>-<%= slug %>.mdx
---
---
slug: <%= slug %>
title: <%= name %>
date: <%= date %>
authors: [author]
description: A brief description
tags: [blog, other_tags]
---

<!-- truncate -->

Content goes here... Add your blog post text.

In the prompt.js file, you can define the prompts to collect user input. For example:

const today = new Date().toISOString().split('T')[0]; // Gets the current date in YYYY-MM-DD format

module.exports = [
{
type: 'input',
name: 'name',
message: 'What is the name of the blog post?',
validate: input => input ? true : 'Blog post name cannot be empty.' // Ensure input is not empty
},
{
type: 'input',
name: 'slug',
message: 'Enter a URL slug for the blog post:',
default: (answers) => {
console.log("Creating slug from:", answers.name); // Ensure 'name' is logged
return answers.name.toLowerCase().replace(/\s+/g, '-').replace(/[^\w-]+/g, '');
},
validate: input => input ? true : 'Slug cannot be empty.' // Validate slug is not empty
},
{
type: 'input',
name: 'date',
message: 'Date for the blog post (YYYY-MM-DD):',
default: today // Sets the default value to today’s date
}
];

Step 3: Create a New Blog Post Using Hygen

hygen blog new
✔ What is the name of the blog post? · test
✔ Enter a URL slug for the blog post: · test
✔ Date for the blog post (YYYY-MM-DD): · 2024-06-05

Loaded templates: _templates
added: blog/2024-06-05-test.mdx

After running the command, a new blog post file will be created in the blog directory with the specified name, slug, and date.