# 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
You can highlight certain lines by adding a single line number or range of line numbers in curly brackets:
<<< @/filepath{1,5-10}
# Example
Say you have a Python file at docs/til/hello.py. You can display the entire file with:
<<< @/docs/til/hello.py
def hello(name):
return f"Hello {name}"
if __name__ == "__main__":
print(hello(input("Name: "))) 2
3
4
You can highlight the first two lines using:
<<< @/docs/til/hello.py{1-2}
def hello(name):
return f"Hello {name}"
if __name__ == "__main__":
print(hello(input("Name: ")))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>
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: ")))2
3
4
5
6
We can display it using:
<<< @/docs/til/hello_with_region.py#snippet
def hello(name):
return f"Hello {name}" Thank you for reading my blog! If you enjoyed this post, you're welcome to subscribe via RSS here (opens new window).