카테고리 없음

Express - nunjucks macro

두비_ 2022. 6. 20. 22:21
반응형
//base.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>{{ title }}</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
    <div class="container" style="padding-top: 10px;">
        <nav class="navbar navbar-inverse"> 
            <div class="container-fluid"> 
                <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-9">
                    <ul class="nav navbar-nav">
                    
                       

                        <li>
                            <a href="/admin/products">List</a>
                        </li>
                        <li class="active"><a href="/admin/products/write">Write</a></li>
                       
                    </ul> 
                </div> 
            </div> 
        </nav>

        {% block content %}{% endblock %}

    </div>    
</body>
</html>

 

코드 상에 나와있듯이 List 클릭 시 /admin/products를 바라보고 write 클릭 시 active를 바라보게 지정한다

현재 URL에 접근이 가능해야하니 변수를 추가한다

app.use((req, res, next) => {
  app.locals.req_path = req.path;
  next();
});

req.path는 Express에서 현재 URL로 전해주는 함수이다

base.html body 최상단에 코드를 req_path를 추가한다

{{req_path}}

현재 URL이 추가된 걸 확인할 수 있다

<li {% if req_path = 'admin/products'%}>
	 <a href="/admin/products">List</a>
</li>
 <li {% if req_path = 'admin/products'%}>

이렇게 URL을 지정할 수 있지만 URL이 많아질 수록 반복작업이 되니 매크로로 하나 만들어주고 깔끔하게 만들 수 있다

template > macro 폴더 생성 > link.html 파일 생성

{#
    href : 링크
    text : 링크안에 들어갈 텍스트
    current_url : 현재 url
#}

{% macro link ( href , text , current_url ) %}
    <li {% if href == current_url %} class="active" {%  endif %}>
        <a href = "{ {href} }">{ {text} }</a>
    </li>
{% endmacro %}

nunjucks에 link 라는 함수를 만들고 주소, 텍스트, 현재 url이 일치하면 class = active를 활성화 해라 라는 뜻이다

이제 링크를 만들었으니 링크를 불러온다

현재 base.html body에 있는 코드가 nunjucks macro로 바꿀 수 있게 되었다

<li>
	<a href="/admin/products">List</a>
</li>
<li class="active"><a href="/admin/products/write">Write</a></li>

변경

{% from "macro/link.html" import link %}
{{ link ( '/admin/products' , "List" , req_path )}}
{{ link ( '/admin/products/write' , 'Write' , req_path ) }}

첫번째 줄을 보면 우리가 Import link를 지정했는데 link.html에서 볼 수 있듯이 macro link 라는 Link 함수를 만들었기 때문에

import link를 지정하는것이다