I followed this tutorial and integrated Django and VueJs using django-webpack-loader, now the main.js output from django-webpack-loader is loading to my index.html
This is my project directory structure
- assets
- bundles
- app.js
- js
- components
- Demo.vue
- index.js
- db.sqlite3
- manage.py
- myapp
- myproject
- node_modules
- package.json
- package-lock.json
- requirements.txt
- templates
- webpack.config.js
- webpack-stats.json
My Demo.vue
component has been imported to the index.js
and using webpack.config.js
file all necessary file has been bundled together to app.js
.
My question is what is the next step? For example, if I have some VueJs components and want to use them in some of my templates how should I do that? Should I create components in the component directory and bundle them all? If this is the case how should I choose to use or not use a component in a specific template? And how should I use Django template tags to insert dynamic data? Or I should write my components in another way?
I know there is multiple questions here, but I couldn't find a good reference to answer my questions so any help would be appreciated.
Django uses a templating language, called Jinja, to pass context (information) from view to template. Assuming that
myapp
is a Django app, you should have amyapp/views.py
file by default.In
myapp/views.py
, you have the ability to create a view (code that is run when a specific URL is accessed). For example, your view could look something like:Then, in
template.html
*, you can use Jinja to parse your context (accessmy_variable
's value). Your template doesn't have to be an HTML file, it can be anything (JS, PHP, etc.), it's just the template file that's loaded from your view.You can use Jinja with Javascript too:
Jinja supports a variety of functionality, including loops, if blocks, and custom functions (tags). Read more: https://codeburst.io/jinja-2-explained-in-5-minutes-88548486834e
If you're using static files that are NOT in your template file, you'll have to serve them as static files. This is a little more complicated, but not hard! You'll have to use a third party library for serving these files in production, like whitenoise. Here's a great tutorial for Django static files, as this extends past the scope of this question.
*Best practice is to make a directory
myapp/templates
and puttemplate.html
in that directory. Then, point Django to yourtemplates
folder insettings.py
: