Layouts and templates help organize pages in a web app. They make your site look consistent and easier to build.
0
0
Layout vs template difference in NextJS
Introduction
When you want the same header and footer on many pages.
When you need different page structures for different sections of your site.
When you want to reuse a common page style but change the content inside.
When you want to separate page design from page content for easier updates.
Syntax
NextJS
export default function Layout({ children }) { return ( <html> <body> <header>Site Header</header> {children} <footer>Site Footer</footer> </body> </html> ) } function Template() { return ( <div> <h1>Page Title</h1> <p>Page content here</p> </div> ) }
Layout wraps pages and adds common parts like header and footer.
Template is the page content inside the layout.
Examples
This layout adds a menu and footer around any page content.
NextJS
export default function Layout({ children }) { return ( <div> <nav>Menu</nav> {children} <footer>Footer info</footer> </div> ) }
This template shows the main content for the home page.
NextJS
export default function Template() { return ( <main> <h2>Welcome!</h2> <p>This is the home page.</p> </main> ) }
Sample Program
This example shows a Layout component that adds a header and footer around the page content. The Template component is the actual page content inside the layout. The Page component combines them to render a full page.
NextJS
import React from 'react'; function Layout({ children }) { return ( <html lang="en"> <body> <header style={{backgroundColor: '#eee', padding: '1rem'}}> <h1>My Website</h1> </header> <main>{children}</main> <footer style={{backgroundColor: '#eee', padding: '1rem', marginTop: '2rem'}}> <p>Ā© 2024 My Website</p> </footer> </body> </html> ); } function Template() { return ( <section> <h2>About Us</h2> <p>We build simple and clear websites.</p> </section> ); } export default function Page() { return ( <Layout> <Template /> </Layout> ); }
OutputSuccess
Important Notes
Layouts wrap around templates to keep site design consistent.
Templates hold the unique content for each page.
Using layouts and templates helps you avoid repeating code.
Summary
Layouts provide the common page structure like headers and footers.
Templates are the unique content inside layouts.
Together, they make building and maintaining pages easier and cleaner.