A cikin ci gaban yanar gizo, nuna bayanai daga uwar garken akan shafukan yanar gizon yana da mahimmanci don ƙirƙirar ƙwarewar mai amfani mai ma'amala da kuzari. Wannan shi ne inda Template Engine aka Express.js zo don ceto. A Template Engine kayan aiki ne da ke ba ka damar ƙirƙirar samfuran HTML masu ƙarfi ta hanyar shigar da bayanai daga uwar garken zuwa lambar HTML.
Me yasa Amfani Template Engine ?
Template Engine taimaka raba HTML markup daga bayanan da ke fitowa daga uwar garken. Wannan yana ba ku damar sarrafa lambar HTML cikin sauƙi ba tare da shigar da bayanai cikin kowane layi na lamba ba. Madadin haka, zaku ƙirƙiri "masu sanya wuri" ko "tags" a cikin lambar HTML, wanda Template Engine daga baya zai cika da bayanan gefen uwar garke.
Amfani Template Engine da in Express.js
Express.js yana goyan bayan nau'ikan template engine, kamar Pug(wanda aka fi sani da Jade) da EJS(Embedded JavaScript). A ƙasa akwai misalan amfani da Pug da EJS a cikin Express.js:
Yin amfani da Pug Template Engine
Sanya Pug: Kuna buƙatar shigar da pug
kunshin ta npm.
npm install pug --save
Sanya Template Engine: A cikin fayil ɗin sanyi na aikace-aikacenku(misali, app.js
), ayyana Pug azaman template engine.
app.set('view engine', 'pug');
Ƙirƙiri Samfuran Pug: Ƙirƙiri fayilolin Pug a cikin views
kundin adireshi. Misali, ƙirƙirar index.pug
fayil:
doctype html
html
head
title My Express App
body
h1 Welcome to My Express App
p #{message}
Gudanar da Hanya da Ba da Bayani: A cikin sarrafa hanya, zaku iya ƙaddamar da bayanai zuwa ta template engine amfani da res.render()
.
app.get('/',(req, res) => {
const message = 'Hello from Express!';
res.render('index', { message });
});
Yin amfani da EJS Template Engine
Shigar da EJS: Shigar da ejs
kunshin ta npm.
npm install ejs --save
Sanya Template Engine: Ƙayyade EJS a matsayin a template engine cikin tsarin aikace-aikacen ku.
app.set('view engine', 'ejs');
Ƙirƙiri Samfurin EJS: Ƙirƙiri fayilolin EJS a cikin views
kundin adireshi. Misali, ƙirƙirar index.ejs
fayil:
<!DOCTYPE html>
<html>
<head>
<title>My Express App</title>
</head>
<body>
<h1>Welcome to My Express App</h1>
<p><%= message %></p>
</body>
</html>
Gudanar da Hanyoyi da Ba da Bayani: A cikin sarrafa hanya, wuce bayanai zuwa template engine amfani da res.render()
.
app.get('/',(req, res) => {
const message = 'Hello from Express!';
res.render('index', { message });
});
Kammalawa
Yin amfani Template Engine da ciki Express.js yana ba ku damar ƙirƙirar shafukan yanar gizo masu ƙarfi da nuna bayanai daga uwar garken akan burauzar mai amfani. Ta amfani da Pug, EJS, ko wasu template engine, za ku iya gina shafukan yanar gizo masu mu'amala da sassauƙa waɗanda ke ba da ƙwarewar mai amfani mafi kyau da haɓaka sarrafa lambar HTML da bayanai.