How to Create Partials Using EJS for Reusable Code 🚀

WHAT TO KNOW - Sep 14 - - Dev Community

<!DOCTYPE html>





How to Create Partials Using EJS for Reusable Code 🚀

<br> body {<br> font-family: sans-serif;<br> line-height: 1.6;<br> margin: 0;<br> padding: 0;<br> }</p> <div class="highlight"><pre class="highlight plaintext"><code> h1, h2, h3, h4, h5, h6 { font-weight: bold; margin-top: 2rem; } pre { background-color: #f5f5f5; padding: 1rem; border-radius: 5px; overflow-x: auto; } code { font-family: monospace; } .container { max-width: 800px; margin: 0 auto; padding: 2rem; } </code></pre></div> <p>




How to Create Partials Using EJS for Reusable Code 🚀



Introduction



In the world of web development, where efficiency and maintainability are paramount, the concept of reusable code is a cornerstone of good practice. One powerful way to achieve this is through the use of partials, which allow you to break down your HTML templates into smaller, modular components. This article will delve into the realm of EJS (Embedded JavaScript Templates) and explore how to leverage partials to create more efficient and elegant web applications.



EJS is a popular templating engine that seamlessly integrates with Node.js. Its intuitive syntax and ability to render dynamic content have made it a favorite among developers. By utilizing EJS partials, we can abstract common elements of our templates, allowing for cleaner code, easier updates, and a more organized project structure.



Imagine a website where you have a repeating header and footer across multiple pages. Instead of duplicating this code on every page, we can encapsulate it into partials and simply include them as needed. This not only reduces redundancy but also makes updating our website a breeze, as a single change in the partial will automatically reflect across all pages using it.



Key Concepts, Techniques, and Tools



EJS (Embedded JavaScript Templates)



EJS provides a way to embed JavaScript code within your HTML templates. This allows you to dynamically generate content, loop through data, and create conditional logic, all within your HTML files. EJS uses a simple syntax with tags that resemble those found in standard HTML. For example, to render a variable called "title" within your EJS template, you would use the following code:



<h1><%= title %></h1>


EJS partials are files with the .ejs extension that represent reusable portions of your templates. These partials can be included within other EJS files using the include directive:



<% include header.ejs %>


Node.js



EJS is typically used in conjunction with Node.js, a JavaScript runtime environment that provides a powerful platform for building server-side applications. Node.js allows you to create web servers, handle user requests, and render EJS templates. You can install EJS using npm (Node Package Manager):



npm install ejs


Practical Use Cases and Benefits



Example: A Blog Website



Let's imagine we're building a simple blog website using EJS. We have a common layout for our posts, including a header, a sidebar with recent posts, and a footer. Using partials, we can streamline this process:



1. Header Partial (header.ejs)



<header>
<h1>My Blog</h1>
<nav>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/about">About</a></li>
<li><a href="/contact">Contact</a></li>
</ul>
</nav>
</header>


2. Sidebar Partial (sidebar.ejs)



<aside>
<h2>Recent Posts</h2>
<ul>
<% for (const post of recentPosts) { %>
<li><a href="/posts/<%= post.id %>"><%= post.title %></a></li>
<% } %>
</ul>
</aside>


3. Footer Partial (footer.ejs)



<footer>
<p>© 2023 My Blog</p>
</footer>


4. Blog Post Template (post.ejs)



<% include header.ejs %>
    &lt;main&gt;
        &lt;article&gt;
            &lt;h1&gt;&lt;%= post.title %&gt;&lt;/h1&gt;
            &lt;p&gt;&lt;%= post.content %&gt;&lt;/p&gt;
        &lt;/article&gt;

        &lt;% include sidebar.ejs %&gt;
    &lt;/main&gt;

    &lt;% include footer.ejs %&gt;
    </code></pre>


In this example, we've broken down our blog post layout into three partials: header, sidebar, and footer. Our post.ejs template then includes these partials, creating a complete and structured page. The benefits of this approach are clear:



  • Reduced Code Duplication:

    The header, sidebar, and footer code only exist in one place, eliminating the need to repeat it for every blog post.


  • Easier Updates:

    If we want to change the navigation menu in the header, we only need to modify header.ejs. The change will automatically propagate to all pages that include it.


  • Improved Organization:

    Our project structure is more organized and manageable with partials.






Step-by-Step Guide: Creating EJS Partials







1. Create Project Structure






Start by creating a new directory for your project. Within this directory, create two subdirectories: "views" and "public".






├── views

│ ├── header.ejs

│ ├── sidebar.ejs

│ ├── footer.ejs

│ ├── post.ejs

│ ├── index.ejs

│ └── about.ejs

└── public






The "views" directory will hold our EJS templates, while "public" will contain static files like CSS, JavaScript, and images.







2. Create Partials (header.ejs, sidebar.ejs, footer.ejs)






Create the files header.ejs, sidebar.ejs, and footer.ejs within the "views" directory. Fill in the HTML content for each partial as shown in the previous blog post example.







3. Create Main Template (post.ejs)






Create the post.ejs file within the "views" directory. This file will include the partials and render dynamic content based on a blog post object:






<% include header.ejs %>
    &lt;main&gt;
        &lt;article&gt;
            &lt;h1&gt;&lt;%= post.title %&gt;&lt;/h1&gt;
            &lt;p&gt;&lt;%= post.content %&gt;&lt;/p&gt;
        &lt;/article&gt;

        &lt;% include sidebar.ejs %&gt;
    &lt;/main&gt;

    &lt;% include footer.ejs %&gt;
    </code></pre>


4. Create Node.js Server



Create a file named app.js in the root directory of your project. This file will set up a Node.js server and handle requests to render our EJS templates:






const express = require('express');

const ejs = require('ejs');
    const app = express();
    const port = 3000;

    app.set('view engine', 'ejs');
    app.set('views', './views');

    app.get('/', (req, res) =&gt; {
        res.render('index', { title: 'Welcome to My Blog' });
    });

    app.get('/posts/:id', (req, res) =&gt; {
        const postId = req.params.id;
        const post = {
            id: postId,
            title: `Post ${postId}`,
            content: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.'
        };
        res.render('post', { post });
    });

    app.get('/about', (req, res) =&gt; {
        res.render('about', { title: 'About Us' });
    });

    app.listen(port, () =&gt; {
        console.log(`Server listening on port ${port}`);
    });
    </code></pre>


This code sets up an Express.js server and configures EJS as the view engine. The server handles different routes, renders appropriate templates, and passes data to those templates.




5. Run the Server






Open your terminal or command prompt and navigate to the root directory of your project. Run the following command to start the Node.js server:






node app.js






The server will now be running on port 3000. Open your web browser and visit http://localhost:3000 to view your blog website.







6. Add Static Files






Create a CSS file in the "public" directory (e.g., style.css) and link it to your EJS templates. You can also add JavaScript files or images as needed.







7. Data Management






In a real-world application, you would likely fetch data from a database or API to populate your blog posts. EJS provides the flexibility to handle this data dynamically. You can modify the Node.js server to retrieve data from a database and pass it to your EJS templates.







Challenges and Limitations






While partials offer significant advantages, they also come with some potential challenges:






  • Complexity with Large Projects:

    In very large projects, managing numerous partials can become complex. You might need to implement a more sophisticated structure to keep track of all your components.


  • Performance Overhead:

    Including many partials on a single page could slightly impact page loading time. Optimize your partials to minimize unnecessary code and consider caching mechanisms.






Comparison with Alternatives






EJS is not the only templating engine available. Other popular choices include:






  • Pug (formerly Jade):

    A popular alternative known for its concise and elegant syntax.


  • Handlebars:

    A powerful templating engine that provides a more structured and data-driven approach.


  • Mustache:

    A lightweight templating engine with a simple and easy-to-learn syntax.





The choice of templating engine depends on your project requirements and personal preferences. EJS offers a balance between simplicity and flexibility, making it a good choice for many web development projects.







Conclusion






Utilizing EJS partials is a powerful way to improve the efficiency and maintainability of your web applications. By breaking down your templates into reusable components, you can reduce redundancy, streamline updates, and create a more organized project structure. This approach allows you to focus on the logic and content of your application, while minimizing the repetition and complexity of your HTML code.






As you continue your journey as a web developer, understanding the concepts of templating engines and partials will be invaluable in crafting efficient and maintainable applications. Experiment with EJS, explore other templating options, and embrace the power of reusable code to elevate your development process.







Call to Action






Ready to dive deeper into EJS and partials? Try out the example project outlined in this article and explore the wealth of resources available online. Don't hesitate to experiment with different templating engines and find the best fit for your projects. The world of web development is vast and exciting; embrace the power of reusable code and build amazing applications.







. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player