I am created documentation using tripit/slate. All documentation content is in .md file. slate is using redcarpet markdown engine. Now when I put <script> tag as below in markdown:
```
<script>document.write(window._restapiurl);</script>
```
it will be converted to <script>document.write(window._restapiurl);</script> in html. And the statement is in <pre> tag so will render as <script>document.write(window._restapiurl);</script> on page. The statement prints the path of an api endpoint.
I want to execute this statement on a page which means the statement should print the value of a varible window._restapiurl. If I manually write the <script> tag in html after page build, the statement will be executed and print the value of a variable.
Update:
tried with :escape_html => true, :filter_html => true in config.rb but it didn't work.
more update
I need to execute javascript statement in my language selector curl tab.
more update
Even If I remove triple ticks ```, the script tag does not execute. It just prints the script statement on a page.
How do I execute javascript code written in markdown ??? So that I don't need to update the api endpoint path whenever new version is released and I can manage it by changing the value of variable only.
In md file I've replaced
```
url of api endpoint
```
with below code
<pre>
<script>document.write(window._restapiurl);</script>
</pre>
This will execute javascript statement in darkbox of tripit/slate documenation format.
Do you really need to put this inside a code block ? If no, just put the script tag inside your Markdown file (or even, FWIW, write <pre><code> yourself). Otherwise, you can't easily do that. The fact is that by default, Redcarpet's HTML render object will escape any HTML tag inside code blocks. Your only option is to implement a custom render object. You can rely on the fact that the code yielded to the block_code method isn't HTML-escaped:
class CustomRender < Redcarpet::Render::HTML
def block_code(code, lang)
"<pre>" \
"<code class=\"#{lang}\">#{code}</code>" \
"</pre>"
end
end
And then pass this object to your Redcarpet::Markdown instance:
Redcarpet::Markdown.new(CustomRender, fenced_code_blocks: true)
Moreover, you're maybe doing it wrong. If it's just about inserting some special values inside your code snippets, then you may want to use a special syntax inside your snippets and replace it with your very own values. You can do that inside a custom render object again, using String#gsub or String#% on the given code variable.
Have a nice day!
Related
So im my view (made with using Blade templates) I have link with href that calls Controller directly, that looks like:
<a id="#{{user.id}}" href="{{action('Controller#method')}}>update</a>
and it works fine, but now I need to pass some additional data, which is taken from vue.js array, which also should be put in curved braces, like:
<a id="#{{user.id}}" href="{{action('Controller#method', ['user_id' => #{{user.id}}])}}>update</a>
and here I start getting messages about unexpected { symbol. I've tried removing # symbol, and putting this variable outside href quotes, but it didn't work. Is there any possibility to solve this?
UPD: I also tried putting this link in vue method, like
$.getJSON('{{action("Controller#method", ["user_id" => '+vm.user.id+'])}}')
but in this case literally "vm.user.id", not variable gets passed in link
UPD2:
I'm now trying to pass data not in link, like $.getJSON('{{action("Controller#method")}}', {user_id: vm.user.id})
and I'm getting links like update?user_id=123, but I need format like update/123
I'm really not familiar with vue.js, but in general PHP would execute on server, and javaScript on client. So first line
<a id="#{{user.id}}" href="{{action('Controller#method', ['user_id' => #{{user.id}}])}}>update</a>
has this part #{{user.id}} PHP can't understand, as it's javaScript notation, so you get some kind of syntax error.
And for second line
$.getJSON('{{action("Controller#method", ["user_id" => '+vm.user.id+'])}}')
I think that this could not get executed either since this doesn't load Laravel, and to PHP {{action("Controller#method")}} has no particular meaning without Laravel loaded.
You could do something like this. Hardcoding part of URL that will render from server, and adding rest of the URL when it goes to client.
For example you can have server generate URL like this:
<a id='url' href="http://example.com/controller/method/">update</a>
And then have some kind of javascript function on client that would append vm.user.id to it when page loads
$(document).ready(function(){
$('#url').attr('href', $('#url').attr('href') + vm.user.id);
});
I think this would result in having an URL like this
<a id='url' href="http://example.com/controller/method/123">update</a>
I am able to get the value of '${currentNode.identifier}' in JSP javascript functions.
When I put the same js function and try to access the '${currentNode.identifier}' inside clientlibs javascript file , it simply outputting the string. not the actual identifier.
**
How to access the current node identfier inside a client libe js file
or inside a listener js function ?
**
I appreciate all the help.
Thanks,
Sri
As rakhi already mentioned in the comment: JavaScripts are delivered "as is" and are not executable servlets like JSPs. So there will be no replacement of scriptlets and ${} attributes. So the easiest way is to have a data attribute on a DIV or any other HTML element which is rendered by a JSP:
<div data-nodeid="${currentNode.identifier}"></div>
Then you could use a jQuery selector to get the value on load:
jQuery(function() {
jQuery('div[data-nodeid]').each(function() {
var nodeId = jQuery(this).data('nodeid');
//do something with the id
});
}
Suppose I go
$( '#' + subform_id ) .load( "subform.php" );
where '#' + subform_id is the ID of a DIV
... is there any way the PHP in subform.php can find out, within its PHP code, the identity of the DIV? (e.g. using its own JS code <script> section)
Or otherwise refer to it by some mechanism without knowing its ID? (e.g. to use JQ's append())
Obviously I could pass the subform_id as a param of the data object (2nd param of load()). But I'm just wondering...
later
followed up on what I thought Victor2748 was suggesting... but in fact it was the ID of a <SCRIPT> block in the injected file which I used to gain access to the existing JS DOM.
Victor2748: if you read this, I'm not sure how you could know the "id of the parent container of your subform.php page" without somehow passing this id as a param in the load() function's data object...
even later
Every comment in this thread says something intelligent! In fact, concerning the question of specifying that this is a PHP file, I'm still trying to get my head around something: obviously it is possible to access the DOM when JS runs in the client. But if your PHP code needs to know the name of the DIV into which it's being loaded I believe you do indeed have to pass this through _POST or _GET. I think there are many reasons why injected PHP code might need this sort of info, e.g. so it can contain code which at some point injects more PHP into the same DIV...
Although... clearly that injection code will inevitably use a JS/JQ script, so maybe that would be the appropriate time to find out what you need about where you are in the DOM.
In JavaScript, you can use this.parentNode to get the parent container, and use this.parentNode.id to get the parent div's id.
Here is an example how your loaded block can get itself as an object/node:
var loadedBlock = document.getElementById("nameOfYourDownloadedParentContainer")
Then you can use loadedBlock.parentNode to get its parent element, then you can get any parameter from it, to identify the element/div.
Update:
First you need to get the node of the current executing <script> tag:
var arrScripts = document.getElementsByTagName('script');
var currentScriptTag = arrScripts[arrScripts.length - 1];
Then, to get the parent of the script tag, use: currentScriptTag.parentNode
(I did not test it yet, please tell me if it helped)
I think so... if you have a script tag in subform.php and the file has the following HTML: Submit form, you should be able to:
var subformId = $('#mydiv').parent().id;
It would work because the script tag executes when the PHP file is included. Put the script tag at the end of subform.php to be sure.
Here is my question, I am using jsp script, trying to match a key word in requesting url and do something:
<script>
$url = '${pageContext.request.requestURL}';
if("${fn:contains(url, 'key')}" == true){
...
}
....
But this doest work... I am not sure where the problem is but I want it to be like when url contains this string, go in to the if condition.
Thank you
You are mixing JSP/EL and JavaScript as if they run in sync. This is wrong. JSP/EL runs in webserver and produces HTML code which get executed in webbrowser. JavaScript (JS) is part of the generated HTML code and runs in webbrowser only.
You need to do it either fully in JSP/EL, or fully in JavaScript. You can use JSP/EL to dynamically generate JS code which get later executed when the page arrives at browser. Rightclick page in browser, do View Source to see what JSP/EL has generated. You should not see any line of JSP/EL. You should only see HTML/JS code. It's exactly that JS code which get executed then.
You're using a JSP EL function to test a JS variable which isn't in the variable scope at that moment at all. This is not going to work. It can only test JSP/EL variables.
Here's how you could do it in pure JS:
<script>
var url = window.location.href;
if (url.indexOf('key') > -1) {
// ...
}
</script>
If you really insist in doing it using JSP/EL, you could do as follows:
<script>
var url = '${pageContext.request.requestURI}';
if (${fn:contains(pageContext.request.requestURI, 'key')}) {
// ...
}
</script>
This will then generate the following JS code (rightclick page in browser and View Source to see it):
<script>
var url = '/some/uri';
if (true) {
// ...
}
</script>
But this makes no sense. Whatever functional requirement you need to solve, you need to think twice about the right approach. Feel free to ask a new question about solving the concrete functional requirement the proper way.
If you want a parameter that the page was requested with, use ${param.paramName}. So in this case ${param.key}. See implicit objects in the docs. And if you just want to check it has a value try ${not empty param.key}.
We are building large ASP.NET applications for the intranet use in multiple languages/cultures. We utilize the Globalization with RESX files and use GetResourceText on the server side to get the localized texts.
Lately we are doing more and more client side logic with JQuery.
How do I get the RESX texts to be used in Javascript?
e.g. texts used for validation, dynamic messages etc.
All our Javascripts are in .JS files, we do not want to mix HTML in the ASPX page and Javascript blocks.
Thanks for your help.
Unfortunately, in an external JS file the server side code is not being processed by the server. However I have seen a workaround where you can set your translated values in hidden fields on the page - this way your javascript will be able to read the values in.
For example:
<%-- This goes into your page --%>
<input type="hidden" id="translatedField" name="translatedField" value="<%=Resources.Resources.translatedText %>" />
and use this inside your javascript file:
// This is the js file
$(document).ready(function() {
alert($("#translatedField").attr("value"));
});
You will be able to separate the values and still see it in your external JS file.
There is also another workaround that creates a .aspx file that only outputs Javascript instead of HTML. Check out the link below:
Using server side method in an external JavaScript file
Always separate functionality from human readable strings.
If you're creating jQuery-plugins you should be able to pass an array of localized strings as parameter when you call your different jQuery functions. The array could be defined as inline javascript directly on the page calling the different jQuery plugins or you could load the from external resource in the format /scripts/localization/strings.js?ci=en-US and register a Generic ASP.Net Handler in web.config that would respond to scripts/localization/strings.js
The DatePicker control is a fine example of how to localize text for the jQuery datepick control - this js file is dynamically created from resource files (resx) and when included on a page it will make sure the calendar control will have danish text.
Create a HttpHandler (.ashx file), and return JSON with your text resource strings.
You may also "publish" it to global namespace, i.e.
Response.Write("window.Resources=");
Response.Write((new JavaScriptSerializer()).Serialize(strings));
set up HTML like:
<script src="Resx.ashx?lang=en-US" />
<button class="LogoutButtonResourceId OtherButtonClasses">(generic logout text)</button>
<a href="#"><span class="SomeLinkTextResourceId OtherClasses">
(generic link text)
</span></a>
and apply texts like this:
$(document).ready(function() {
for(var resId in Resources){
$("."+resId).html(Resources[resId]);
}
});
If you don't want to use ASP.NET to generate your main JavaScript, here are two other options:
Use ASP.NET to generate a script file that contains variable-to-string assignments, such as var mystring = 'my value';. Your main script would then reference the localized text with variables names rather than as embedded values. If that's still too "dirty" for you, you could encode the strings as JSON rather than as variable assignments, using an HttpHandler rather than straight .aspx.
Have your JavaScript code issue an Ajax call to retrieve an array or list of localized strings from the server. The server-side part of the call would retrieve the text from your resx files.
Have you considered using $.ajax in combination with ASP.NET WebMethods? It's hard to suggest a more concrete solution to this problem without understanding how your JavaScript/jQuery would consume/process the resources. I assume that they're organized into logical groups (or could be) where you could return several resource strings that belong on a single page.
Assuming that, you could write a very simple C# class -- or use a Dictionary<string, string> -- to return data from your ASP.NET WebMethod. The results would look something like:
[WebMethod]
public Dictionary<string, string> GetPageResources(string currentPage)
{
// ... Organizational stuff goes here.
}
I always separate out my AJAX calls into separate .js files/objects; that would look like:
function GetPageResources (page, callback)
$.ajax({ // Setup the AJAX call to your WebMethod
data: "{ 'currentPage':'" + page + "' }",
url: /Ajax/Resources.asmx/GetPageResources, // Or similar.
success: function (result) { // To be replaced with .done in jQuery 1.8
callback(result.d);
}
});
Then, in the .js executed on the page, you should be able to consume that data like:
// Whatever first executes when you load a page and its JS files
// -- I assume that you aren't using something like $(document).ready(function () {});
GetPageResources(document.location, SetPageResources);
function SetPageResources(resources) {
for (currentResource in resources) {
$("#" + currentResource.Key).html(currentResource.Value);
}
}
I know it's to late but want share my experience in this task)
I use AjaxMin. It can insert resx key values into js file on build event.
It's not common way but it keeps html without unneeded script blocks and can be done during minification process if you have it.
It works like this:
ajaxmin.exe test.js -RES:Strings resource.resx -o test.min.js
Also you need to do the same for ech locale if you have many.
Syntax to write resource keys in js (and also css) is written here:
Js localization
Css localization
How about injecting it as part of a javascript control initialization? what i do is as follows:
I have a self-contained javascript control - call it CRMControl, which has an init method called setupCRMControl, to which i pass a settings object. When i initialize it, i pass an object containing all the resources i need inside javascript as follows:
CRMControl.setupCRMControl({
numOfCRMs: 3,
maxNumOfItems: 10,
// then i pass a resources object with the strings i need inside
Resources: {
Cancel: '#Resources.Cancel',
Done: '#Resources.Done',
Title: '#Resources.Title'
}
});
Then, inside this javascript control:
var crmSettings = {};
this.setupCRMControl(settings) {
crmSettings = settings;
};
and whenever i want to show a resource, i say (for example, show an alert saying 'Done'):
alert(crmSettings.Resources.Done);
You can call it "R" to make it shorter or something, but this is my approach. Maybe this may not work if you have a whole bunch of strings, but for manageable cases, this may work.