mariusbalcytis / webpack-bundle

Bundle to Integrate Webpack into Symfony
MIT License
122 stars 36 forks source link

Variable webpack_asset #60

Open woutsluiter opened 7 years ago

woutsluiter commented 7 years ago

I'm trying to include a different logo per locale:

{{ webpack_asset('@app/Resources/assets/images/logo-' ~ app.request.locale ~ '.svg') }}

But the compiler trows this error: Argument passed to function webpack_asset must be text node to parse without context.

Any suggestions on how to handle this sort of thing?

mariusbalcytis commented 7 years ago

In general, similar feature could be added as variables in assetic.

I tried to avoid it as it's usually best to include JavaScript files conditionally inside other JavaScript files - Webpack itself handles this pretty nicely and this results in "better" asset files (no duplicated content across different assets, better caching, conditional loading etc.) In this case, it's the image that's being loaded, so it's a no-go for Webpack itself if you want it to load instantly.

For the moment, you could do this manually:

{{ app.request.locale == 'en'
        ? webpack_asset('@app/Resources/assets/images/logo-en.svg')
        : (
            app.request.locale == 'de'
                ? webpack_asset('@app/Resources/assets/images/logo-de.svg')
                : webpack_asset('@app/Resources/assets/images/logo-es.svg')
        )
}}

Or by splitting into separate if-else statements.

I think variables would be nice, though. In such case it would be something like

{{ webpack_asset('@app/Resources/assets/images/logo-{locale}.svg', variables= {locale: app.request.locale} ) }}

And you would also need to configure all possible values for locale variable in config.yml file.

woutsluiter commented 7 years ago

That would be nice indeed. For now I think i will load it the old fashioned way.

vicnicius commented 7 years ago

@mariusbalcytis would you be willing to accept a pull request to implement such feature? I would love to give it a try.

mariusbalcytis commented 7 years ago

For now, I'm thinking about another option how this could be handled. Webpack parses the code and sees the patterns where variables in the string takes place, then searches files by these patterns. I think this option would be less complicated to set-up and would work out-of-the-box in most cases.

For variables:

With parsing concatenation:

So, I'm going towards the second option - the given example would work out-of-the box in this case.

I'm planning to look into this, so reopening the issue. @vicnicius feel free to make a pull request if you're up to it, though.