alphagov / govuk-frontend

GOV.UK Frontend contains the code you need to start building a user interface for government platforms and services.
https://frontend.design-system.service.gov.uk/
MIT License
1.19k stars 328 forks source link

Using the Rails asset pipeline for images #730

Closed tijmenb closed 6 years ago

tijmenb commented 6 years ago

In Rails we use helpers to refer to assets in CSS:

background-image: image-url("icon-pointer.png");
background-image: asset-url("icon-pointer.png");

This makes the asset pipeline in Rails work: instead of linking to icon-pointer.png, it will link to the fingerprinted version of the file.

Currently GOV.UK Frontend [just uses url("file.png") in the CSS](), so Rails won't point the correct assets:

https://github.com/alphagov/govuk-frontend/blob/5bb66d62c2f7ad5fb96363f9d54121b510b32ec1/package/tools/_file-url.scss#L4

For GOV.UK to use GOV.UK Frontend, we'll need a way to override the govuk-file-url or to instruct it to use asset-url.

Options

~Defining the function first~

I thought maybe defining the govuk-file-url function above the @import for GOV.UK Frontend would work, but the later definition overrides this.

~Defining the function last~

This doesn't work because govuk-file-url is already used by the CSS.

~Conditionally defining the function~

I though maybe if we wrap the function in a conditional like below, our override might work.

@if function-exists('govuk-file-url') == false {
  @function govuk-file-url($file) {
    @return url($govuk-global-images + $file);
  }
}

Unfortunately SCSS errors out with:

Functions may not be defined within control directives or other mixins.

Conditional inside function

This works:

$govuk-use-rails: true;

@function govuk-file-url($file) {
  @if $govuk-use-rails {
    @return asset-url($file);
  } else {
    @return url($govuk-global-images + $file);
  }
}

This follows a spike into using GOV.UK Frontend on GOV.UK (https://github.com/alphagov/govuk_publishing_components/pull/328).

36degrees commented 6 years ago

Hey @tijmenb,

Thanks for raising – can you take a look at https://github.com/alphagov/govuk-frontend/pull/733 and see if it'll address your needs?

Ta

tijmenb commented 6 years ago

@36degrees tested by hacking it into the PR: https://github.com/alphagov/govuk_publishing_components/pull/328/commits/643c48214639fea3af2405176ccadfb7ee021447. Works well! 👌

NickColley commented 6 years ago

Thanks for the great issue @tijmenb 👍