Can somebody please explain how `let` works with `tp.file.include()`?

I use dates / offsets everywhere. I would like to have a single template fragment that I can use to set variables / do the date math once and then just include this template everywhere.

Here is a simplified example:

/templates/frag/dates.md:

<%*
let ISO_8601_SHORT_FMT = "YYYY-MM-DD";

let today = moment();
let yesterday = moment(today).subtract(1, 'd');
let tomorrow = moment(today).add(1, 'd');

let this_week = moment(today).startOf('isoWeek');
let this_week_num = today.isoWeek();

let last_week = moment(today).subtract(1, 'w').startOf('isoWeek');
let last_week_num = last_week.isoWeek();

let next_week = moment(today).add(1, 'w').startOf('isoWeek');
let next_week_num = next_week.isoWeek();

let week_delta = Math.abs(next_week_num-this_week_num);
// This pattern continues for quarter/year ... etc
*%>

I would then like to have a /templates/daily.md:

<% tp.file.include("[[templates/frag/dates]]") %>

last week number is: <%last_week_num%>
this week number is: <%this_week_num%>
next week number is: <%next_week_num%>

When i create a new note and then try to run templeter with the daily template, I get this error in the console:

VM114:82 Templater Error: Template parsing error, aborting. 
 last_week_num is not defined

But when I create a /templates/dates-combined.md:

<%*
let ISO_8601_SHORT_FMT = "YYYY-MM-DD";
let today = moment();
let yesterday = moment(today).subtract(1, 'd');
let tomorrow = moment(today).add(1, 'd');
let this_week = moment(today).startOf('isoWeek');
let this_week_num = today.isoWeek();
let last_week = moment(today).subtract(1, 'w').startOf('isoWeek');
let last_week_num = last_week.isoWeek();
let next_week = moment(today).add(1, 'w').startOf('isoWeek');
let next_week_num = next_week.isoWeek();
let week_delta = Math.abs(next_week_num-this_week_num);

%>
yesterday: <%yesterday%>
yesterday_str: <%yesterday.format(ISO_8601_SHORT_FMT)%>
today: <%today%>
today_str: <%today.format(ISO_8601_SHORT_FMT)%>
tomorrow: <%tomorrow%>
tomorrow_str: <%tomorrow.format(ISO_8601_SHORT_FMT)%>
last_week: <%last_week.format(ISO_8601_SHORT_FMT)%>
last_week_num: <%last_week_num%>
this_week: <%this_week.format(ISO_8601_SHORT_FMT)%>
this_week_num: <%this_week_num%>
week_delta: <%week_delta%>
next_week: <%next_week.format(ISO_8601_SHORT_FMT)%>
next_week_num: <%next_week_num%>

I get the content that I expect:

yesterday: Mon Jan 31 2022 11:13:51 GMT-0800
yesterday_str: 2022-01-31
today: Tue Feb 01 2022 11:13:51 GMT-0800
today_str: 2022-02-01
tomorrow: Wed Feb 02 2022 11:13:51 GMT-0800
tomorrow_str: 2022-02-02
last_week: 2022-01-24
last_week_num: 4
this_week: 2022-01-31
this_week_num: 5
week_delta: 1
next_week: 2022-02-07
next_week_num: 6

Is there a way to do what I am looking to do?

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.