F
F
fisherspoons2020-11-20 12:19:35
JavaScript
fisherspoons, 2020-11-20 12:19:35

How to refer to a file in twig template?

Hello everyone, I ran into a problem, there is a webpack project, there is a need to use twig templates. And there is a need to insert the most necessary js / css files into the positions I need on the page, disabling the inject function,
the file names contain dynamic hashes.

new HtmlWebpackPlugin({
      hash: false,
      template: `/index.html.twig`,
      filename: `/index.html.twig`,
      inject: false
    }),

    new MiniCssExtractPlugin({
      filename: `css/[name].[contenthash].css`,
    }),


But there is a BUT, if earlier, when using a regular html file, I could refer to the file like this

new HtmlWebpackPlugin({
      hash: false,
      template: `/index.html`,
      filename: `/index.html`,
      inject: false
    }),

     <link rel="stylesheet" href="<%= htmlWebpackPlugin.files.chunks.base.css %>">
     <script async src="<%= htmlWebpackPlugin.files.chunks.vendors.entry %>"></script>


Then in the twig file such an entry does not roll, if someone has come across a similar one, I will be very obliged

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
svm, 2021-06-10
@fisherspoons

I am writing my own solution for the blade templating engine, but there is no need to be afraid, it is the same there, just the designs are different.
webpack.config.js:

new HtmlWebpackPlugin({
            template: "resources/js/template_vanilla.ejs",
            filename: path.resolve(__dirname, 'resources/views/inline/vanilla.blade.php'),
            inject: false,
            publicPath: '/assets',
        }),

template_vanilla.ejs:
<% let styles = htmlWebpackPlugin.files.css; %>
<% let scripts = htmlWebpackPlugin.files.js; %>

<% for (let style of styles) { %>
    <link rel="stylesheet" href="<%= style %>">
<% } %>

<% for (let script of scripts) { %>
    <script src="<%= script %>"></script>
<% } %>

After execution, the following code will be in resources/views/inline/vanilla.blade.php:
<script src="/assets/js.ebb3174236087eacfa7b.bundle.js"></script>

which can be included with the usual construction
In my case it will be @include('inline.vanilla')
In yours, probably {% include 'resources/views/inline/vanilla.blade.php' %}
In fact, only change the file names to the ones you need remains for you.
I did all this so that the cache for users in browsers was automatically reset and there was no need to manually edit it. And so that the code is more or less clean.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question