ptheofan
ptheofan

Reputation: 2280

SASS generating URLs for multiple static

The idea is that I use some mixin to generate domain for the images. Assuming I have 2 domains which have the same images I want to be able to load half the images from one domain and half from another.

in PHP this is something like

$domains = array('domain1', 'domain2', 'domain3');
$domainIdx = 0;

function getDomain(){
    $rVal = $domains[$domainIdx];
    $domainIdx = $domainIdx++ >= count($domains) ? 0 : $domainIdx++;
    return $rVal;
}

which I call every time I render an image to get a domain for it. How could I do something similar in a mixin in SASS so when CSS is generated it will distribute all URLs between the domains list?

Upvotes: 0

Views: 133

Answers (2)

piouPiouM
piouPiouM

Reputation: 5037

In your Compass configuration file (ie. config.rb), you can use the asset_host function, like this:

asset_host_list = ['domain.com', 'domain.org']
asset_host do |asset|
  "http://%s" % asset_host_list[asset.hash % asset_host_list.length]
end

But, I agreed with @cimmanon, this approach is weak.

Upvotes: 1

Actually, you can port exitsting code to SASS pretty straightforwardly:

$domains:        'domain1.com' 'domain2.org' 'domain3.net'
$current-domain: 1

@function get-domain()
  $domain: nth($domains, $current-domain)
  $current-domain: $current-domain + 1
  @if $current-domain > length($domains)
    $current-domain: 1
  @return $domain

You can then use it like this:

@for $i from 1 through 10
  .element-#{$i}
    background-image: url("http://#{get-domain()}/images/foo.png")

Demo: http://sassbin.com/gist/5831644/

Also, you've got a couple of bugs in your PHP snippet. The correct code would be:

$domains = array('domain1', 'domain2', 'domain3');
$domainIdx = 0;

function getDomain(){
    global $domains, $domainIdx;
    $rVal = $domains[$domainIdx];
    $domainIdx = $domainIdx + 1>= count($domains) ? 0 : $domainIdx + 1;
    return $rVal;
}

And @cimmanon is absolutely right. Such approach to load balancing is amateurishness and poor practice.

Upvotes: 0

Related Questions