Pug

PussinSocksΒ·2022λ…„ 7μ›” 20일
0

CloneCoding

λͺ©λ‘ 보기
10/20

How to return HTML from ExpressJS?

One way of returning it is by writing whole HTML documents on the controller and send out.
Ex)

export const see = (req, res) => {
    return res.send(`<!DOCTYPE><HTML><head></head><body></body></HTML>`);
};
  • But you can see it right away this is not the best way to do it. So we use

Pug

Pug is a high performance template engine heavily influenced by Haml and implemented with JavaScript for Node.js and browsers. link to pug

  • you can simply install pug through terminal
    npm i pug
  • Setting up pug as the HTML view engin
//server.js
app.set("view engin", "pug");
  • Then Express will use pug to return HTML

How to set views?

  • Create views folder inside src folder
  • Create name.pug file inside of views folder as HTML file.

The pug file have different syntax from HTML

//Example
doctype html
html(lang="en")
  head
    title= pageTitle
    script(type='text/javascript').
      if (foo) bar(1 + 5)
  body
    h1 Pug - node template engine
    #container.col
      if youAreUsingPug
        p You are amazing
      else
        p Get on it!
      p.
        Pug is a terse and simple templating language with a
        strong focus on performance and powerful features.
  • You don't need opening and closing tags. Everything is distinguished with tabs and distnaces.

How to send this .pug file browser?

  • In the conroller:
res.render("home");
  • but you will see an error on the browser:
    Error: Failed to lookup view "home" in views directory "/Users/followthesnake/Desktop/youtubeclone/views"
  • Meaning the file is not in the right place.
  • Run console.log(process.cwd()); (cwd means Current Working Directory
  • /Users/nameOfTheUser/Desktop/youtubeclone
  • youtubeclone starts from here, more specifically, the server starts from package.json in the youtubeclone folder. Not in the src folder.

Two Solutions

  1. Take out the views folder outside from the src folder.
  2. you can config the pug engine directory:
    ```javascript
    //server.js	
    app.set("views", process.cwd() + "/src/views");
    ```
    (Definately the second solution is the answer)

Partials

partials are used for repetitive components like footer. Since you don't want to type the same thing for every single pages, you separate the component and just include the filename to the pages you need to.

  • Create "partials" folder inside "views" folder.
  • Create the .pug file inside with scripts in it
  • Type include partials/filename.pug to the pug file you want to attach the footer.

Extending Templates

  • Further more, when you make a website, there gonna be tones of pages to script. Repetitive and similary pages. In order to minimize the time to type same stuff, There is a solution called "Inheritance"

Inheritance

Inheritance is like a mold. You can make files with same structure over and over again, easy and fast.Just like you use same variables over and over again.

  1. Make a base.pug (names can be anything, but I think layout.pug is the common name for it).
//base.pug
doctype html 
html(lang="kr")
    head 
        title Home | YoutubeClone
    body 
        Home
    include partials/footer.pug

This structure is going to be inherited to the files you want by putting

//home.pug
extends base.pug

block

Block is a window. When you need same structure but different contents inside of the each page, you can use block.

//base.pug
doctype html 
html(lang="kr")
    head 
        title Home | YoutubeClone
    body 
         block content //This is the block.
    include partials/footer.pug

⬇ Extended to home.pug

//home.pug
extends base.pug

block content 
    h1 Home
  • on each extended file, you can make different content with block like this.

Pug variables

//base.pug
doctype html 
html(lang="kr")
    head 
        title #{pageTitle} | YoutubeClone //This is the variable
    body 
         block content
    include partials/footer.pug
  • Where do I set the value? => at the controller
res.render("home", { pageTitle: "Home" });
${variableName} 
tagName=variableName
// both are same
  • What's the difference?

    First one with ${} is used when the variable is mixed with other text. and =variableName is used when only one variable is there to use.


Conditionals

if else

//In a controller with a dummyUser
const fakeUser = {
    username: "Koodal",
    loggedIn: false,
}

export const trending = (req, res) => res.render("home", { pageTitle: "Home", fakeUser });

We had to write fakeUser: fakeUser in an older version of JS, but after ES6, now we can write it like above.

 body 
        header 
            if fakeUser.loggedIn 
                small Hello #{fakeUser.username}!
            nav 
                ul 
                    if fakeUser.loggedIn
                        li  
                            a(href="/logout") Log out
                    else
                        li
                            a(href="/login") login

We can put conditionals inside of pug. (Feels like I'm making conditionals with HTML right away 🀩)


Iterations

// controller
export const trending = (req, res) => {
    const videos = [1,2,3,4,5,6];
    res.render("home", { pageTitle: "Home", videos });
};
//home.pug
	each variableName in arrayname
		li=variableName
	else something you can write

variableName in each variableName in arrayname can be anything as long as the arrayname is right.


mixins

Works like a partials but receives data.
Premade HTML block.

Mixins are used to make same format of a component.
For example, this project is cloning Youtube. And When you go inside the youtube, you see thumbnames(videos) all over in every single pages.

Video thumbnails are there when you first go to Youtube, while you're watching a video, there's a sidebar shows more videos related to the video you're watching or related to you're interest.

To make a website like youtube, you need some sort of a frame which can iterate data. And that is mixins

How to apply mixins?

  1. Create a mixins folder in a view folder.
  2. Create a .pug file inside the mixins folder.
  3. Make a syntax to iterate
//Example array inside a controller
    const videos = [
        {
            title: "Planet of Apes",
            rating: 4.3,
            comments: 23,
            createdAt: "2 minutes ago",
            views: 220,
            id: 1,
        },
        {
            title: "Planet of Apes 2",
            rating: 4.3,
            comments: 23,
            createdAt: "2 minutes ago",
            views: 220,
            id: 1,
        },
        {
            title: "Planet of Apes 3",
            rating: 4.3,
            comments: 23,
            createdAt: "2 minutes ago",
            views: 220,
            id: 1,
        },
	mixin video(info)
    div
        h4=info.title  
            ul 
                li #{info.rating}/5
                li #{info.comments} comments
                li Posted: #{info.createdAt}
                li #{info.views} views total
//home.pug
extends base
include mixins/video

block content 
    each video in videos
        +video(video)

video from videos gets iterated in the +video(video). and each video info interates and shows on the browser.


More info about Pug: Pug Documentation

profile
On a journey to be a front-end developer

0개의 λŒ“κΈ€