开发者

how to reference background image urls in css through config entrys

While specifing background image urls in css can we get the value from a config entry.

Today my serve开发者_JS百科r name is http://imageserver , tomorrow it may change to http://imagecacheserver.

How can i change at one place so that there is no need to change in all the css files.

On the .net side , i get the server url from appsettings.


Are you using .Net MVC? Even if you're using WebForms you can incorporate MVC (just have a quick Google).

Anyway, if so you could put in a UrlRoute in Global.asax

routes.MapRoute(
                "ImageHandler",
                "images/{*fileName}",
                new { controller = "ImageHandler", action = "Handle", fileName = "" } 
            );

Then just add an 'ImageHandler' controller that does the following:

public class ImageHandlerController : Controller
    {
        public ActionResult Handle(string fileName)
        {
            return Redirect("http://myactualserver.com/imageshere/" + fileName);
        }

    }

This will then redirect all HTTP GET requests from /images/* to the dynamic Url. Of course you can then just "jazz-up" the method above to use the Url that you have in your AppSettings rather than the hard-coded string. You may also want to HtmlEncode 'fileName' to be safe.

So your CSS code can now just use background-image: url("/images/blah.jpg") regardless of where the files actually are.


If you make careful use of relative urls, this is not a problem. Consider this:

.testclass { background: url(http://mydomain.com/images/myimage.jpg); }

This is fine - so long as you're still set up on mydomain.com. An alternative:

.testclass { background: url(/images/myimage.jpg); }

This will work on any domain you stick it on, assuming that there's an /images folder. As long as you're consistent and your file structure stays the same, you're good to go. All this assumes you're hosting your images and CSS/HTML on the same domain, of course.


I have the solution for you! It's called LESS! LESS is a CSS framework that extends CSS, that lets you create variables, mixins and nested rules. LESS uses the CSS syntax so you just have to add a variable to your existing CSS.

In your case:

@path: "http://myserver.net/images";


body {
  background-image: url(%("%s/bg-body.jpg", @path));
}

Then you just have to compile your CSS and upload it the server. When your image server changes you just have to change the variable, compile the CSS and upload it.

Of course if this is just for one image is overkill, but if you have a CSS with hundreds of declarations it's really nice to hava a solution like this.

You can visit LESS website at http://lesscss.org/


If you are using Apache as a web server, you can also create a reverse proxy, so that every request to '/images/...' get redirected internally for 'http://sever2.com/images/..'

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜