Will html image paths still work after precompile? - html

I'm building a Rails app, but I'm using a plugin in which I have to render my images using only html.
Since I haven't deployed yet, all my images are in RAILS_ROOT/app/assets/images/, so to render an image I have to write the following code:
<img src="/assets/image.jpg">
But when I'm ready to deploy to the web and I perform a precompile, all my images are supposedly going to be moved to my public folder. Will the html still work to link to the image, or will I have to change to link to a different path?
The plugin I'm using is Typeahead:
application.html.erb*
<script type="text/javascript">
//....
$('#typeahead').typeahead(null, {
maxLength: 5,
displayKey: function(thing) {
return "<div class='typeahead'><img src='" + thing.image_url + "'></div>";
},
source: bloodhound.ttAdapter(),
});
</script>
things_controller.rb
def typeahead
#render json: Thing.where(name: params[:query])
q = params[:query]
render json: Thing.where('name LIKE ?', "%#{q}%")
end
*Thing.image_tag is currently set to "/assets/[image.jpg]", except for each thing it's adjusted with the proper file name.

Not only are they going to be in the public folder, but they'll be renamed to include the fingerprint.
You must use the Rails helpers for all assets, see how to here and read the rest of the guide while you're at it :)

I think you should use non-stupid-digest-assets gem as it copies all your assets(mentioned in assets precompile list) in public/assets folder and then you need not to change your code before/after compiling.To install, you just need to add it into your Gemfile.
gem 'non-stupid-digest-assets'
I hope it might help you.

Joe, my suggestion would be to create a directory in your public folder to house your images, instead us using the app/assets directory. The public folder will allow the assets to not be altered by the rails pipeline, and you can link to them reliably using any external services that need the images.
As stated in RailsGuides:
Assets can still be placed in the public hierarchy. Any assets under
public will be served as static files by the application or web server
when config.serve_static_files is set to true. You should use
app/assets for files that must undergo some pre-processing before they
are served.
So you would need to add this line in config/application.rb
config.serve_static_files = true
As described in Rails general configuration.

It looks like you're storing your image_url in your model, and that's not working because assets don't have fixed URLs in Rails. I would override the getter in your model to use the asset_path helper, so it translates the path when that attribute is read (e.g., when the JSON is generated).
Something like:
# thing.rb
[...]
def image_url
ActionController::Base.helpers.asset_path(read_attribute(:image_url))
end
[...]

Short answer, no.
But it isn't that big a deal to remedy. Just move the images you need to reference with html into your Public folder. Then you can simply reference them with this code:
<img src="/image_name.image_type">
and the html will link to the correct path, both before and after precompile. So you don't have to change any code before you deploy.
BTW: I assume image_tag and image_url are the same column and you just made a mistake in one of the two times you mentioned it. If that's the case, then don't forget to change it to simply "/[image.jpg]".

Related

Serving Polymer App to a /path not at root

So the first thing I want to do with a new Polymer app is deploy to a directory on an existing website. The only thing that seems to work is deploying to root /.
Let's take the Shop example. I do:
polymer init and choose shop
polymer build
Robocopy.exe .\build\bundled\ C:\inetpub\wwwroot\p\ /MIR
start http://localhost/p/
You see I'm on Windows. I assume that using IIS is irrelevant, since I'm relying on the server just to serve static content.
What do I need to edit in the shop template to make it work at the url http://localhost/p/?
The polymer-cli created apps came with assumption of serving from root level '/'. In generated project index.html you will find two comments
<!--
The `<base>` tag below is present to support two advanced deployment options:
1) Differential serving. 2) Serving from a non-root path.
Instead of manually editing the `<base>` tag yourself, you should generally either:
a) Add a `basePath` property to the build configuration in your `polymer.json`.
b) Use the `--base-path` command-line option for `polymer build`.
Note: If you intend to serve from a non-root path, see [polymer-root-path] below.
-->
<base href="/">
<!-- ... -->
<script>
/**
* [polymer-root-path]
*
* By default, we set `Polymer.rootPath` to the server root path (`/`).
* Leave this line unchanged if you intend to serve your app from the root
* path (e.g., with URLs like `my.domain/` and `my.domain/view1`).
*
* If you intend to serve your app from a non-root path (e.g., with URLs
* like `my.domain/my-app/` and `my.domain/my-app/view1`), edit this line
* to indicate the path from which you'll be serving, including leading
* and trailing slashes (e.g., `/my-app/`).
*/
window.Polymer = {rootPath: '/'};
// ...
</script>
if in this index.html file you comment out base tag and set window.Polymer rootPath to something like '/0/polymer-test/build/es5-bundled/' you will be able to navigate in app on http://localhost/0/polymer-test/build/es5-bundled/
The Polymer shop-app assumes it will be deployed on the server root. Therefore it has all of the links and routes hard-coded to that assumption.
This means, that you will have to change all of the following:
all absolute links between the pages,
all pattern parameters in app-route elements (this is not necessary when useHashAsPath = true),
all absolute imports, including the lazy ones via importHref,
update the absolute locations within the service worker (use instructions from here) and
all references to static content (CSS, images, JS files)
I'm guessing your main goal isn't porting the shop-app, but rather future proofing your own app so that it can also be deployed to non-root locations on the server.
For this, I will mention two ways, depending on which value of useHashAsPath you use for the app-location element. This setting defaults to false, which means that you must use full URLs, instead of the hashbang equivalents.
Scenario 1: useHashAsPath = true
This is the easiest of both approaches, since you simply treat all URLs between the pages as absolute links. For example: Tabs.
The next step is to reference all static content and imports via relative links.
The last step is to update your service worker as shown here.
Scenario 2: useHashAsPath = false
If you dislike the hashbang URLs, go for this scenario. As you can figure out, this approach is a bit more difficult, but still manageable (especially when you start from scratch).
Firstly, you should still use absolute links, since relative links between a complex routing scheme can quickly cause problems (e.g. when not all pages are on the same directory level).
But since absolute links are a no-go, you will have to add some additional pre-processing upon build time. The point is to prefix all links with, say __ROOT__, and then replace all of those values with your actual document root. The links would then look like something this:
Some page
And you would use gulp-replace or something similar to replace __ROOT_ with /your-document-root across all of your source files in order to produce something like this:
Some page
At this point, you've got your links fixed. But this is only part of the problem. You must also apply the same fix to all of your app-route elements. For example:
<app-route pattern="__ROOT__/some/page" [...]></app-route> // Other parameters ommited
As with other resources, such as images and CSS files, you can also include them as absolute links and add the __ROOT__ prefix, but I would advise against this and would rather use relative paths.
The last step is to update your service worker as shown here.
Read more about routing: https://www.polymer-project.org/1.0/blog/routing

Yii2 add google font to head

I was wondering how do you add link tag/google font to head in yii2.
I want to add the following
<link href='http://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700' rel='stylesheet' type='text/css'>
I have found this documentation but doesn't mention anything about link/adding google font etc
The correct answer is to create a new AssetBundle.
While you can directly place the HTML for the fonts into the of your main.php file, this isn't the Yii way. If you have tried to load jQuery files this way, you might notice odd behavior when directly putting them into the HTML.
For example: Directly place the HTML tag for Bootstrap CDN into the head of your main.php. Then, somewhere in your code try to use the tooltip. You will get an error in your console that tooltip is not a function. - This is because the way Yii puts all your template files together, and at that time, Bootstrap is not available.
While simply loading a font probably won't cause any problems, it is a good idea to do things the way they were intended. Following MVC rules, properly documenting your code, and following the Yii best practices, will go a long way. Not only will you thank yourself a year later when you have to go back into a project, but the next guy will appreciate it. I can't stand going into systems, and seeing stuff thrown everywhere, chincy hacks, and spaghetti code, and no documentation or comments.
Correct Way:
Create a new AssetBundle. In your assets folder, you probably already have AppAsset.php. Duplicate it, and name it FontAsset.php.
Here is an example from my project, using 3 Google fonts.
FontAsset.php
<?php
namespace app\assets;
use yii\web\AssetBundle;
class FontAsset extends AssetBundle
{
public $basePath = '#webroot';
public $baseUrl = '#web';
public $css = [
'//fonts.googleapis.com/css?family=Open+Sans:400,700',
'//fonts.googleapis.com/css?family=Ubuntu:400,700',
'//fonts.googleapis.com/css?family=Oswald:400,700'
];
public $cssOptions = [
'type' => 'text/css',
];
}
In your layout, main.php for example. Right under where you see AppAsset::register($this)
main.php
use app\assets\FontAsset;
FontAsset::register($this);
For every layout file that you want to load those fonts, include the FontAsset.
The AssetBundle is basically a bundle of CSS and/or JS files and options. You could add another one for say JWPlayer say named VideoAsset, and add your JS/CSS files for JWPlayer in it.
Point being, you shouldn't be adding these things directly into the HTML of the layouts directly, as it can cause problems. Let the AssetManager handle them by declaring AssetBundles.
It might save you later down the road!
The best way is to create an asset bundle and add the link to the bundle.
You can find a complete guide here:
http://www.yiiframework.com/doc-2.0/guide-structure-assets.html
You can put it directly in the head of the layout (file views/layouts/main.php)

Get an absolute link from a relative one in Freemarker

I'm creating a site using Magnolia - CMS. Now I am implementing a blog page. On each blog page, there are several share buttons. Now I'm busy implementing the twittershare button. Here I am going to use the twitter cards. For that, I need to provide the URL of an image in a metatag. Main problem: I retreive my image like this: ${damfn.getAssetLink(content.blogImage)}. This only returns a relative path to my resource. Is there a quick way (in freemarker), that will convert tis to an absolute link?
Many thanks in advance!
usually you define magnolia.default.base.url in the magnolia.properties.
then you can retrieve it with Components.getComponent(ServerConfiguration.class).getDefaultBaseUrl()
now you have to install the service into freemarker. you can do that by adding installer-tasks into the renderers on startup. you do that in your module-version-handler. there you overwrite the getStartupTasks(...), something like this:
#Override
protected List<Task> getStartupTasks(InstallContext installContext) {
final List<Task> tasks = new ArrayList<>();
tasks.add(new InstallRendererContextAttributeTask("rendering", "freemarker", "serverConf", ServerConfiguration.class.getName()));
tasks.add(new InstallRendererContextAttributeTask("site", "site", "serverConf", ServerConfiguration.class.getName()));
return tasks;
}
now you can call in freemarker:
"${serverConf.defaultBaseUrl}/${ctx.contextPath}/${damfn.getAssetLink(content.blogImage)}"
checkout if the slashes are necesarry and make sure that defaultBaseUrl is set properly in your magnolia configuration ("/server/...")
edit: there should be an easier by calling the current request in freemarker ${Request} so it could be something like "${Request.domain}/${ctx.contextPath}/${damfn.getAssetLink(content.blogImage)}" without injecting the serverConfiguration into the renderer

Sinatra serving images in HTML

So I currently have a very simple Sinatra server. I have a public folder that has css, js, and images as folders within it. In my view when I try to do something like <img src="/images/blah.png">, I get a 404 response. I thought the default of the public folder is public. I feel like I'm not including something or doing something stupid. I am using bootstrap and the css & js files are served fine. It isn't clear to me why I'm getting this 404 with the images?
This is how I'm running my application
#!/usr/bin/env ruby
$: << File.dirname(__FILE__)
require 'load_test_ui.rb'
unless ARGV[0].nil?
class LoadTestUI < Sinatra::Base
set :port, ARGV[0]
end
end
LoadTestUI.run!
It was indeed a stupid mistake; I wasn't URI encoding the source. When I changed the name to just blah.png, it rendered correctly!

Assets(images, css) url resolution for actions in Rails

what's the best approach for making reference for assets, for nested urls.
e.g. if in my html I refer to image this way: , it does not work when the url is myapp/admin/edit/1 or any custom url.
Use the asset tag helpers, image_tag and so on:
http://api.rubyonrails.org/classes/ActionView/Helpers/AssetTagHelper.html
Wherever your current path is should make no difference, as accessing assets should be done from root, e.g. /images/whatever.jpg, /stylesheets/whatever.css
The asset tag helpers will make this transparent, and additionally, they will transform paths for you if you ever use an asset host other than your web server. For example.
# if you define a different asset_host, Rails will handle it.
ActionController::Base.asset_host = "assets.example.com"
image_tag("rails.png")
# => <img alt="Rails" src="http://assets.example.com/images/rails.png?1230601161" />