Drupal 7 template views preprocess add javascript: what am I doing wrong? - javascript

I have read that the best-practice to add a javascript file to a particular view is to use the preprocessor and drupal_add_js. What I'm trying to add is a Facebook app script. I know the script works, because I've tested just adding it in tags right in the header of the view.
What isn't working for me is the code I've added to my theme's template.php file below. As far as I can tell from searching, this should work (obviously replacing THEME_NAME and VIEW_NAME with the actual names), but the js file is just not being added. I also tried just adding it to every page in my theme's .info file, just to see if it would work adding it to every page, but no luck.
function THEME_NAME_preprocess_views_view(&$vars) {
$view = $vars['view'];
if ($view->name == 'VIEW_NAME') {
drupal_add_js(drupal_get_path('theme', 'THEME_NAME') . '/js/facebook.js');
}
}

Just call preprocess for each view. For help visit this link
function bartik_preprocess_views_view(&$vars) {
$function_name = __FUNCTION__ . '__' . $vars['view']->name;
if (function_exists($function_name)) {
$function_name($vars);
}
}
function bartik_preprocess_views_view__test(&$vars) {
$view = $vars['view'];
if ($view->name == 'test') {
drupal_add_js(drupal_get_path('theme', 'bartik') . '/js/facebook.js');
}
}

Related

net::ERR_ABORTED) How can I solve js file path issue in the Template's plugins (Converting Bootstrapt to WordPress)

I'm converting Bootstrap Template to WordPress.
I cannot load dynamic slide, I guess there is a trouble to access js file.
Error Message from Chrome console.
enter image description here
in my functions.php
function theme_js() {
wp_enqueue_script('script_js', get_template_directory_uri() .
'/js/script.js', array('jquery'), '', true );
}
add_action('wp_enqueue_scripts', 'theme_js');
However, in the scripts.js file there is a code to return a specific path.
var PLUGINS_LOCALPATH = '/plugins/';
-------------(more)-----------------
getScriptLocation: function() {
var location = $('body').data('plugins-localpath') || null;
if (location) {
return location;
}
return PLUGINS_LOCALPATH;
},
so this will try to reach such as "http://localhost/wordpress.test/plugins/slider-revolution/revolution/js/jquery.themepunch.tools.min.js?v=5.4.4" this kinda path, but I think wordpress need to use php based path like
I am wondering how can I solve this issue.
could you give me some solutions? thank you.
Hi i actually had a simmilar problem today and my solution was really simple.
I updated my word press and all was fixed.

Cannot include wysiwyg.js script in Jade with Node.js

While trying to create a rich text editor, I cannot seem to add the js script for the buttons and form. Right now, most of the functions are inlined in the jade pages, but that is quite unelegant.
I have a layout.jade file:
doctype html
html
head
body
header
section.content
block content
And the create.jade script, where I want the rich text editor:
extends ../layout
block content
script(type='text/javascript', src='./css/js/wiz.js')
form(method="post", action=post ? '/post/edit/' + post.id : '/post/create', onload="iFrameOn()")
ul
p
input#title(name="title", placeholder="Title", value=post ? post.title : '', autocomplete='off')
p
#wysiwyg_cp(style="padding:8px; width:700px")
input(type="button", onClick="iBold();", value="B")
input(type="button", onClick="richTextField.document.execCommand(\"underline\",false,null);", value="U")
p
textarea#blogPostBody(style="display:none", name="blogPostBody", placeholder="Blog post text", rows="20", cols="50")
iframe#richTextField(name="richTextField", contentEditable="true", onLoad="richTextField.document.designMode = 'On';")
if(post)
| #{post.body}
else
| &#09
p
input(onClick="javascript:submit_form();", type="button", name="myBtn", value="Save")
The structure of the project looks like:
Proj
- css
-- js
--- wiz.js
- middleware
- node_modules
- public
- routes
- views
-- post
--- create.jade
-- layout.jade
-- home.jade
-- login.jade
- app.js
- package.json
When trying to open the create section of my blog, I get the following error message, as can be seen in the image below:
Uncaught SyntaxError: Unexpected token <
See chrome stack: http://i.stack.imgur.com/JyHs2.png
The wiz.js file looks like this:
function iFrameOn() { richTextField.document.designMode = 'On'; }
function iBold() { richTextField.document.execCommand("bold",false,null); }
function iUnderline(){ richTextField.document.execCommand("underline",false,null); }
function iItalic(){ richTextField.document.execCommand("italic",false,null); }
function iImage() {
var imgSrc = prompt("EnterImageLocation", '');
if(imgSrc!=null) {
richTextField.document.execCommand("insertimage",false,imgSrc);
}
}
function submit_form() {
var theForm = document.getElementById("myForm");
theForm.elements("myTextArea").value = window.frames['richTextField'].document.body.innerHTML;
theForm.submit();
}
I have also tried adding
app.set('view options', {locals:{scripts:['wiz.js']}});
and/or adding
app.use(express.static("./css/js"));
In the app.js file or in the middleware.
But these did not help. The problem seem to be in the "create.jade" script, when referencing the 'text/javascript' script, because the same error was obtained even when referencing a non-existant js file.
Could anyone have any idea what the problem could be?
[EDIT] SOLUTION that was implemented:
script
include ./../../css/js/wiz.js
The following snippet of code worked:
script
include ./../../css/js/wiz.js
Express's static middleware will by default mount the files to the root. So, if you include the middleware as above, the wiz.js file will be accessible at "/wiz.js" when your server's running -- this is the path you should put in the src attribute of your script tag in the jade file, not the local path (since local files are not accessible to the client unless they are served). If you want to change the mountpath (so, for example, that the file will be accessible on "/js/wiz.js", rather than the root), you can add it as a first argument, like below:
var localDirectoryPath = "./css/js";
// Or if you happened to want an absolute path
// (though it doesn't make a difference here):
// var localDirectoryPath = require("path").join(__dirname, "css", "js");
app.use("/js", express.static(localDirectoryPath));
The temporary solution that you've found (using Jade's include function) is merely loading the file's contents on the server (when Jade compiles the template) and inserting the code in between script tags on your page, which works but is certainly not ideal, since it will slow down the initial loading of your HTML, especially as the wiz.js file gets bigger.
And I won't even ask why your javascript directory is inside your css directory!

How to inject code from one text file into an HTML page

I have a series of large html pages in development, each uses a common structure: header / content / sidebar.
Header and sidebar sections have code common to all pages. Only content changes.
During the development phase, I want to be able to make changes to the header and sidebar once and see the results replicated on all pages without having to edit each page separately.
I've done a bit of googling, and the simplest solution seems to be to create 2 separate text files with the code for the header and sidebar sections, and then inject this at the appropriate points in the HTML pages I'm editing.
I know this is not recommended for a live project, as it would dramatically increase the load times, but for dev work it would save me a lot of time.
Would you agree? If so, anybody have any idea what the simplest way to do this is?
Thanks
You would be better to do this with some sort of server-side technology, like PHP. This would make the impact on loading times negligible as the pages would be concatenated before they were sent to the browser.
You would accomplish it by doing something like this:
<?php require('header.php'); ?>
<!-- Main content goes here -->
<?php require('sidebar.php'); ?>
And then have the files header.php and sidebar.php in the same directory as the main files.
Use some sort of serverside templating languate that would allow for you to include files within each other.
If, despite the other answers, you insist on doing this from JavaScript, the following is a module I use :
(function xload (slctr) { //================================================== xload ===
function xloader (src, dst) {
if (arguments.length == 1) {
dst = src;
src = dst.getAttribute ('data-source') || '';
}
var req;
try {
src = src.match (/^([^]*?)(!)?(?:\[\[([^]*?)\]\])?$/);
(req = new XMLHttpRequest ()).open ('GET', src[1], !src[2]);
req.onreadystatechange = function (ev) {
if (this.readyState === 4) {
if (typeof dst == 'function')
dst (req);
else {
dst[dst.tagName == 'TEXTAREA' ? 'value' : 'innerHTML'] = this.responseText;
[].forEach.call (dst.getElementsByTagName ('SCRIPT'), function (s, i) {
var script = document.createElement ('script');
script.innerHTML = s.parentNode.removeChild (s).innerHTML;
document.body.appendChild (script);
})
}
}
};
src[3] && req.overrideMimeType &&
req.overrideMimeType (src[3]);
req.send (null);
} catch (err) { console.log ('xloader error : ', err); }
}
[].forEach.call (document.querySelectorAll (slctr), function (el) { xloader (el); });
}) ('[data-source]'); //------------------------------------------------------ xload ---
Any element, a div for example with a data-source attribute is processed. The data-source specifies the url of the file to be included. When he Ajax request completes, the entire contents of the div are replaced with the text fetched. The data-sourc url may optionally be followed by a ! indicating synchronous load and then by a Mime type enclosed in [[ and ]]
Any scripts in the loaded text are extracted and injected into the document body.
Error conditions are reported on the console.
The module is entirely standalone and processes all elements containing the data-source attribute. It should, of course be loaded after the HTML text of the page.

How do I include javascript files server-side?

I want to include JS file inside another JS file, on server side, to prevent copy-paste and multiple JS files loading from client.
Just like include('file.js') as PHP would do.
There is no built in way to include other JavaScript files from a JavaScript file ... but you can add them into the DOM ->
function addJavascript(jsname,pos) {
var th = document.getElementsByTagName(pos)[0];
var s = document.createElement('script');
s.setAttribute('type','text/javascript');
s.setAttribute('src',jsname);
th.appendChild(s);
}
Example usage :
addJavascript('newExternal.js','body');
As Supercharging javascript article suggest - with PHP you can read all your .js files and create one big js file that you will send in one piece.
This is a simplification of the example from the article, just to get you started:
<?php
define('SCRIPT_DIR', $_SERVER['DOCUMENT_ROOT'] . '/script/');
$files = array(
'jquery.js',
'myLib.js',
'site.js'
);
header('Content-Type: text/javascript');
foreach (files as $file) {
if (#readfile(SCRIPT_DIR . $file) === false) {
error_log("javascript.php: Error reading file '$file'");
}
}
?>
I would also recommend to read the full article Supercharging JavaScript in PHP to get more info.
JSfile = "1.js, 2.js, 3.js"
for loop it
document.write();
You will have to use a script loader and i would like to recommend script.js by Dustin Diaz who works at Twitter. Project Page on Github.
Here is how you use it
assuming you have a jquery plugin to be loaded in a page here is what you should do
// load jquery and plugin at the same time. name it 'bundle'
$script(['jquery.js', 'my-jquery-plugin.js'], 'bundle')
// load your usage
$script('my-app-that-uses-plugin.js')
/*--- in my-jquery-plugin.js ---*/
$script.ready('bundle', function() {
// jquery & plugin (this file) are both ready
// plugin code...
})
/*--- in my-app-that-uses-plugin.js ---*/
$script.ready('bundle', function() {
// use your plugin :)
})
example is also from project page. Here are steps you should follow
Load the Script.js file first
Now include the dependency loader script that loads all the other wanted scripts async[the content of dependency loader script would be like above]

ASP.NET MVC including ASP in Javascript

Is it possible to put ASp.NET tags in my javascript which is in a seperate script file. For example, I have the following
$.getJSON("/Postcode/GetAddressResults/" + $get("SearchPostcode").value, null, function(data) {
which I want to turn into but it does not like the ASP tags!
var action = "<%=Url.Content('~/Postcode/GetAddressResults/')%>" + $get("SearchPostcode").value
$.getJSON(action, null, function(data) {
However this does not seem to work, what am I doing wrong?
Add to your master page(s) a meta tag to hold the value of the current applications path from the host (the bit the ~ represents).
In your Javascript create a function which will resolve a ~ prefixed path using the meta tag content.
Edit
Example as requested:-
Place this code in the head section your master pages:-
<meta id="meta.AppDomainAppVirtualPath"
name="AppDomainAppVirtualPath" value="<%=HttpRuntime.AppDomainAppVirtualPath%>" />
In your javascript include this function:-
function resolveUrl(url)
{
if (url.charAt(0) == "~")
{
if (!resolveUrl.appPath)
{
var meta = document.getElementById('meta.AppDomainAppVirtualPath');
resolveUrl.appPath = meta ? meta .getAttribute("content") : '/';
}
if (resolveUrl.appPath == '/')
return url.slice(1, url.length;
else
return resolveUrl.appPath + url.slice(1, url.length);
}
else
{
return url;
}
}
Now your line of code is:-
$.getJSON(resolveUrl("~/Postcode/GetAddressResults/") + $get("SearchPostcode").value, null, function(data) {
If your JavaScript is in a separate script file, then it won't be processed by ASP.NET, so these tags won't be processed. You'll need them inline in an ASP.NET page for this to work.
No, you can`t.
You can expose a path within your view to javascript, but not directly in your external javascript file.
#David M
Inlining the whole thing is not really neccesary, you can inline the dynamic part and leave the other part hardcoded.
Regards, Peter

Categories