banner



Can I Use Php In Ejs Template

Introduction

When quickly creating Node applications, a fast fashion to template your application is sometimes necessary.

Jade comes as the default template engine for Express but Jade syntax tin can be overly complex for many use cases.

Embedded JavaScript templates (EJS) tin can be used as an culling template engine.

In this article, you will learn how to employ EJS to an Express awarding, include repeatable parts of your site, and pass information to the views.

Prerequisites

If you would like to follow along with this commodity, you will demand:

  • A local development environment for Node.js. Follow How to Install Node.js and Create a Local Evolution Environment.

This tutorial was originally written for express v4.17.one and ejs v3.ane.5. It has been verified with Node v16.0.0, npm v7.11.i, express v4.17.1, and ejs v3.1.6.

Footstep one — Setting Upwards the Project

Outset, open your last window and create a new project directory:

                      
  1. mkdir ejs-demo

Then, navigate to the newly created directory:

                      
  1. cd ejs-demo

At this point, you can initialize a new npm projection:

                      
  1. npm init -y

Next, you lot will need to install the express bundle:

                      
  1. npm install express@four.17.ane

So install the ejs package:

                      
  1. npm install ejs@3.one.half dozen

At this signal, you have a new project ready to use Limited and EJS.

Step ane — Configuring with server.js

With all of the dependencies installed, let's configure the application to utilize EJS and gear up up the routes for the Index page and the About page.

Create a new server.js file and open it with your code editor and add together the following lines of code:

server.js

                      var            limited            =            require            (            'limited'            )            ;            var            app            =            express            (            )            ;            // set the view engine to ejs            app.            set            (            'view engine'            ,            'ejs'            )            ;            // use res.return to load up an ejs view file            // index page            app.            go            (            '/'            ,            function            (            req,              res            )            {            res.            render            (            'pages/index'            )            ;            }            )            ;            // about page            app.            get            (            '/about'            ,            part            (            req,              res            )            {            res.            return            (            'pages/almost'            )            ;            }            )            ;            app.            listen            (            8080            )            ;            panel.            log            (            'Server is listening on port 8080'            )            ;                  

This lawmaking defines the application and listens on port 8080.

This code also sets EJS every bit the view engine for the Express application using:

                                    `              app.set('view engine', 'ejs');              `                              

Notice how the lawmaking sends a view to the user by using res.return(). Information technology is important to note that res.return() will look in a views folder for the view. So you only have to define pages/alphabetize since the full path is views/pages/index.

Next, you will create the views using EJS.

Step ii — Creating the EJS Partials

Like a lot of the applications yous build, there will be a lot of code that is reused. These are considered partials. In this example, there will be iii partials that volition be reused on the Index page and About page: head.ejs, header.ejs, and footer.ejs. Let's make those files now.

Create a new views directory:

                      
  1. mkdir views

So, create a new partials subdirectory:

                      
  1. mkdir views/partials

In this directory, create a new head.ejs file and open it with your code editor. Add the following lines of lawmaking:

views/partials/head.ejs

                                                    <meta              charset                              =                "UTF-eight"                            >                                                      <title              >            EJS Is Fun                              </title              >                        <!-- CSS (load bootstrap from a CDN) -->                                          <link              rel                              =                "stylesheet"                            href                              =                "https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/four.5.two/css/bootstrap.min.css"                            >                                                      <style              >                                                      body                {                padding-acme                :50px;                }                                                                    </style              >                              

This code contains metadata for the head for an HTML certificate. It also includes Bootstrap styles.

Next, create a new header.ejs file and open it with your code editor. Add together the following lines of lawmaking:

views/partials/header.ejs

                                                    <nav              class                              =                "navbar navbar-expand-lg navbar-low-cal bg-light"                            >                                                      <a              grade                              =                "navbar-brand"                            href                              =                "/"                            >            EJS Is Fun                              </a              >                                                      <ul              class                              =                "navbar-nav mr-auto"                            >                                                      <li              grade                              =                "nav-item"                            >                                                      <a              class                              =                "nav-link"                            href                              =                "/"                            >            Dwelling house                              </a              >                                                      </li              >                                                      <li              course                              =                "nav-item"                            >                                                      <a              form                              =                "nav-link"                            href                              =                "/about"                            >            About                              </a              >                                                      </li              >                                                      </ul              >                                                      </nav              >                              

This code contains navigation for an HTML certificate and uses several classes from Bootstrap for styling.

Next, create a new footer.ejs file and open information technology with your code editor. Add together the following lines of code:

views/partials/footer.ejs

                                                    <p              form                              =                "text-centre text-muted"                            >                        &copy;            Copyright 2020 The Awesome People                              </p              >                              

This code contains copyright information and uses several classes from Bootstrap for styling.

Next, you will utilize these partials in index..ejs and about.ejs.

Step iii — Adding the EJS Partials to Views

Y'all have iii partials defined. Now you lot can include them in your views.

Use <%- include('RELATIVE/PATH/TO/FILE') %> to embed an EJS partial in some other file.

  • The hyphen <%- instead of just <% to tell EJS to render raw HTML.
  • The path to the partial is relative to the current file.

And so, create a new pages subdirectory:

                      
  1. mkdir views/pages

In this directory, create a new index.ejs file and open up it with your lawmaking editor. Add the following lines of code:

views/pages/index.ejs

                                    <!              DOCTYPE              html              >                                                      <html              lang                              =                "en"                            >                                                      <head              >                                                      <%-                                  include                  (                  '../partials/head'                  )                  ;                                %>                                                                    </head              >                                                      <body              course                              =                "container"                            >                                                      <header              >                                                      <%-                                  include                  (                  '../partials/header'                  )                  ;                                %>                                                                    </header              >                                                      <main              >                                                      <div              course                              =                "jumbotron"                            >                                                      <h1              >            This is cracking                              </h1              >                                                      <p              >            Welcome to templating using EJS                              </p              >                                                      </div              >                                                      </main              >                                                      <footer              >                                                      <%-                                  include                  (                  '../partials/footer'                  )                  ;                                %>                                                                    </footer              >                                                      </torso              >                                                      </html              >                              

Save the changes to this file so run the application:

                      
  1. node server.js

If you visit http://localhost:8080/ in a spider web browser, you tin can discover the Index page:

Screenshot of the index page with head, header, and footer partials rendered

Side by side, create a new well-nigh.ejs file and open it with your code editor. Add together the following lines of code:

views/pages/about.ejs

                                    <!              DOCTYPE              html              >                                                      <html              lang                              =                "en"                            >                                                      <head              >                                                      <%-                                  include                  (                  '../partials/head'                  )                  ;                                %>                                                                    </head              >                                                      <trunk              grade                              =                "container"                            >                                                      <header              >                                                      <%-                                  include                  (                  '../partials/header'                  )                  ;                                %>                                                                    </header              >                                                      <primary              >                                                      <div              course                              =                "row"                            >                                                      <div              class                              =                "col-sm-8"                            >                                                      <div              class                              =                "jumbotron"                            >                                                      <h1              >            This is great                              </h1              >                                                      <p              >            Welcome to templating using EJS                              </p              >                                                      </div              >                                                      </div              >                                                      <div              class                              =                "col-sm-four"                            >                                                      <div              grade                              =                "well"                            >                                                      <h3              >            Look I'grand A Sidebar!                              </h3              >                                                      </div              >                                                      </div              >                                                      </div              >                                                      </main              >                                                      <footer              >                                                      <%-                                  include                  (                  '../partials/footer'                  )                  ;                                %>                                                                    </footer              >                                                      </body              >                                                      </html              >                              

This code adds a Bootstrap sidebar to demonstrate how partials can be structured to reuse across different templates and pages.

Save the changes to this file and and then run the application:

                      
  1. node server.js

If you visit http://localhost:8080/about in a web browser, you can observe the About page with a sidebar:

Screenshot of the About page with head, header, and footer partials rendered and sidebar displayed.

At present you lot can start using EJS for passing data from the Node application to the views.

Step 4 — Passing Information to Views and Partials

Permit's define some basic variables and a list to pass to the Index folio.

Revisit server.js in your code editor and add the following lines of code inside the app.get('/') route:

server.js

                      var            express            =            require            (            'express'            )            ;            var            app            =            limited            (            )            ;            // gear up the view engine to ejs            app.            set            (            'view engine'            ,            'ejs'            )            ;            // use res.return to load upwards an ejs view file            // index folio            app.            get            (            '/'            ,            function            (            req,              res            )            {                          var              mascots              =              [                                      {              proper noun              :              'Sammy'              ,              organization              :              "DigitalOcean"              ,              birth_year              :              2012              }              ,                                      {              name              :              'Tux'              ,              organisation              :              "Linux"              ,              birth_year              :              1996              }              ,                                      {              name              :              'Moby Dock'              ,              organization              :              "Docker"              ,              birth_year              :              2013              }                                      ]              ;                                      var              tagline              =              "No programming concept is complete without a cute creature mascot."              ;                        res.            render            (            'pages/alphabetize'                          ,              {                                      mascots              :              mascots,                                      tagline              :              tagline                          }                        )            ;            }            )            ;            // almost page            app.            get            (            '/almost'            ,            function            (            req,              res            )            {            res.            render            (            'pages/about'            )            ;            }            )            ;            app.            mind            (            8080            )            ;            console.            log            (            'Server is listening on port 8080'            )            ;                  

This lawmaking defines an array called mascots and a string chosen tagline. Next, allow'due south employ them in index.ejs.

Rendering a Unmarried Variable in EJS

To echo a single variable, you can employ <%= tagline %>.

Revisit alphabetize.ejs in your code editor and add the following lines of code:

views/pages/index.ejs

                                    <!              DOCTYPE              html              >                                                      <html              lang                              =                "en"                            >                                                      <head              >                                      <%-                              include                (                '../partials/head'                )                ;                            %>                                                      </head              >                                                      <body              class                              =                "container"                            >                                                      <header              >                                      <%-                              include                (                '../partials/header'                )                ;                            %>                                                      </header              >                                                      <main              >                                                      <div              class                              =                "jumbotron"                            >                                                      <h1              >            This is great                              </h1              >                                                      <p              >            Welcome to templating using EJS                              </p              >                                                                        <h2                >              Variable                                  </h2                                                    >                                                                        <p                >                                            <%=                                  tagline                                %>                                                              </p                                                    >                                                      </div              >                                                      </main              >                                                      <footer              >                                      <%-                              include                (                '../partials/footer'                )                ;                            %>                                                      </footer              >                                                      </body              >                                                      </html              >                              

This code will brandish the tagline value on the Index page.

Looping Over Data in EJS

To loop over data, yous can employ .forEach.

Revisit index.ejs in your code editor and add together the following lines of code:

views/pages/index.ejs

                                    <!              DOCTYPE              html              >                                                      <html              lang                              =                "en"                            >                                                      <head              >                                      <%-                              include                (                '../partials/head'                )                ;                            %>                                                      </head              >                                                      <body              form                              =                "container"                            >                                                      <header              >                                      <%-                              include                (                '../partials/header'                )                ;                            %>                                                      </header              >                                                      <main              >                                                      <div              grade                              =                "jumbotron"                            >                                                      <h1              >            This is groovy                              </h1              >                                                      <p              >            Welcome to templating using EJS                              </p              >                                                      <h2              >            Variable                              </h2              >                                                      <p              >                                      <%=                              tagline                            %>                                                      </p              >                                                                        <ul                >                                                                    <%                                  mascots.                  forEach                  (                  function                  (                  mascot                  )                  {                                %>                                                                                      <li                >                                                                                      <stiff                >                                            <%=                                  mascot.proper noun                                %>                                                              </strong                                                    >                        representing                              <%=                                  mascot.organization                                %>              ,            born                              <%=                                  mascot.birth_year                                                                    %>                                                                        </li                >                                                                    <%                                  }                  )                  ;                                %>                                                                                      </ul                >                                                                    </div              >                                                      </principal              >                                                      <footer              >                                      <%-                              include                (                '../partials/footer'                )                ;                            %>                                                      </footer              >                                                      </body              >                                                      </html              >                              

Save the changes to this file and then run the awarding:

                      
  1. node server.js

If y'all visit http://localhost:8080/ in a web browser, you can observe the Index page with the mascots:

Screenshot of the list of mascots rendered.

Passing Information to a Fractional in EJS

The EJS partial has access to all the aforementioned data as the parent view. Only exist careful. If you are referencing a variable in a partial, information technology needs to exist defined in every view that uses the partial or it will throw an fault.

You tin can also define and pass variables to an EJS partial in the include syntax like this:

views/pages/about.ejs

          ...                                          <header              >                                      <%-                              include                (                '../partials/header'                ,                                  {                  variant                  :                  'compact'                  }                                )                ;                            %>                                                      </header              >                        ...                  

Only yous need to again be careful most assuming a variable has been defined.

If you want to reference a variable in a fractional that may not always be divers, and requite it a default value, you lot can do so similar this:

views/partials/header.ejs

          ...                                          <em              >            Variant:                          <%=                              typeof                variant                !=                'undefined'                ?                variant                :                'default'                            %>                                                      </em              >                        ...                  

In the line above, the EJS code is rendering the value of variant if it'south defined, and default if not.

Conclusion

In this article, you learned how to employ EJS to an Express awarding, include repeatable parts of your site, and laissez passer information to the views.

EJS lets you lot build applications when you exercise not crave boosted complexity. By using partials and having the ability to hands laissez passer variables to your views, you lot can build some great applications apace.

Consult the EJS documentation for boosted data on features and syntax. Consult Comparing JavaScript Templating Engines: Jade, Mustache, Dust and More for understanding the pros and cons of unlike view engines.

Can I Use Php In Ejs Template,

Source: https://www.digitalocean.com/community/tutorials/how-to-use-ejs-to-template-your-node-application

Posted by: carsonadvit1993.blogspot.com

0 Response to "Can I Use Php In Ejs Template"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel