LoginSignup
8
8

More than 5 years have passed since last update.

ejsでテンプレートをインクルードした時にリンクを相対パスで設定する方法

Last updated at Posted at 2016-11-15

ejsでテンプレートをインクルードした時にリンクを相対パスで設定する方法

ejsで<head></head>の部分をテンプレート化してインクルードするとします。
headの中にはcssのリンクがあると思います。

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>タイトル</title>
<link rel="stylesheet" href="css/style.css">
</head>

この時、
/ルート
|_ index.html
|__folder
 |__hoge.html
のようにディレクトリがなっていると、hoge.htmlでcssが読み込めないです。
hoge.htmlでは正しいcssリンクは

<link href="../css/style.css">

だからです。

そんな'../'を自動で付与したい時のメモ

develop
 |_ index.html
 |_folder
  |__index.html
 |__css
  |__style.css
 |__ejs
  |__template
   |_
_head.ejs
  |__index.ejs
  |__folder
   |__index.ejs
のようなディレクトリ構成とします。
前提:gulpの処理でfolder/index.ejsはdevelop/folder/index.htmlに吐き出されるものとする。

htmlになるejsファイル

filenameはそのままfilenameでokです。
filenameにそのファイルの、絶対パスが入っています。
<%- include('template/_head',{absPath:filename}) %>
head.ejs
絶対パスを[develop]からのパスに分割して、[develop]からの距離分../を返してます。


<%
 pathSet = function(absPath){
    var rootPath = absPath.split('develop/ejs')[1];
    if(rootPath.split('/').length - 2 > 0){
        return '../'.repeat(rootPath.split('/').length - 2);
    }else{
        return '';
    }
 };
%>
<link rel="stylesheet" href="<%= pathSet(absPath) %>css/style.css">

これで、../が自動で付与されます。

pathSet関数は別ファイルに分けるのをお勧めします。
自分んはejsフォルダの中にutilフォルダを作ってその中に書いてます。
そのファイルをインクルードすれば、関数も使用できます。

8
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
8