# Including code blocks from files in Vuepress

# Introduction

Today I learned that you can include code snippets from files in Vuepress using the syntax:

<<< @/filepath
1

You can highlight certain lines by adding a single line number or range of line numbers in curly brackets:

<<< @/filepath{1,5-10}
1

# Example

Say you have a Python file at docs/til/hello.py. You can display the entire file with:

<<< @/docs/til/hello.py
1
def hello(name):
    return f"Hello {name}"

if __name__ == "__main__":
    print(hello(input("Name: ")))
1
2
3
4

You can highlight the first two lines using:

<<< @/docs/til/hello.py{1-2}
1
 
 



def hello(name):
    return f"Hello {name}"

if __name__ == "__main__":
    print(hello(input("Name: ")))
1
2
3
4

And you can only display the first two lines using:

# Displaying only certain lines

You can even display only certain lines from a file. However, you'll need to modify your code file to define "code regions."

Vuepress uses the VS Code folding regions (opens new window) syntax to define regions. You have to give the region a name, like # region <snippet-name>. Then you can display only the region using:

<<< @/filepath#<snippet-name>
1

For example, here we define a region with the name snippet:

 


 



# region snippet
def hello(name):
    return f"Hello {name}"
# endregion snippet

if __name__ == "__main__":
    print(hello(input("Name: ")))
1
2
3
4
5
6

We can display it using:

<<< @/docs/til/hello_with_region.py#snippet
1
def hello(name):
    return f"Hello {name}"
1

Newsletter

If you'd like to subscribe to my blog, please enter your details below. You can unsubscribe at any time.

Powered by Buttondown.

Last Updated: 11/20/2023, 10:04:51 AM