How can I use `#let mydate = datetime(...)` from main.typ in included typ

I have this in my main.typ file.

#let mydate = datetime(
  year: 2023,
  month: 05,
  day: 27,
)

// more stuff
#include "text-with-date.typ"

In text-with-date.typ

That THE date, #show context mydate.display(), 

when I run now typst compile main.typ get I

 typst compile main.typ && okular main.pdf
error: expected colon
    ┌─ text-with-date.typ:411:19
    │
411 │ That THE date, #show context mydate.display(),
    │                                          ^

help: error occurred while importing this module

I think this have something to do with Context – Typst Documentation but not sure how to fix it.

Hey alex01,

You could put the mydate declaration into a separate .typ file, so you can include it in main.typ and in text-with-date.typ!

Than you but I get the same error but now in main.

// main.typ
#include "my-functions.typ"
#mydate.display()
// my-functions.typ
#let mydate = datetime(
  year: 2020,
  month: 04,
  day: 27,
)
# typst compile main.typ && okular main.pdf
error: unknown variable: mydate
   ┌─ main.typ:91:1
   │
91 │ #mydate.display()
   │  ^^^^^^

The command here would be to import it.

#import "my-functions.typ": *
1 Like

To add to @quachpas’s answer, here is a complete example!

my-function.typ

#let mydate = datetime(
  year: 2020,
  month: 04,
  day: 27,
)

this-is-another-page.typ

#import "my-function.typ": *

`this-is-another-page.typ` also imports the `mydate`: #mydate.display()

main.typ

Here are a couple of examples, how to include functions. The first is used, when you have multiple packages with the same name, so you just rename them for the scope of this file (in this case main.typ).

The second one is a “filtered” import (I now have coined this term), which allows you to include only specific content of a file/package.

The third allows you to rename imported content!

The fourth includes all the content (so you don’t have to use my-function.mydate.display().

There is also #import "my-function.typ", which imports the module under the same name (hence you can insert your date with my-function.mydate.display())

#import "my-function.typ" as fn
#fn.mydate.display()

#import "my-function.typ": mydate
#mydate.display()

#import "my-function.typ": mydate as hahadate
#hahadate.display()

#import "my-function.typ": *
#mydate.display()

#include "this-is-another-page.typ"

Result

image

If you got any questions, just ask away! That’s what the forum is for!

2 Likes