Embed javascript in markdown - javascript

I'm using the Maruku markdown processor. I'd like this
*blah* blah "blah" in [markdown](blah)
<script src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script>
...do stuff...
</script>
but it complains when I render it with a multitude of errors. The first one being
___________________________________________________________________________
| Maruku tells you:
+---------------------------------------------------------------------------
| Could you please format this better?
| I see that "<script type='text/javascript'>" is left after the raw HTML.
| At line 31
| raw_html |<script src='http://code.jquery.com/jquery-1.4.2.min.js' /><script type='text/javascript'>|
| text --> |//<![CDATA[|
and then the rest seems like the parser is going nuts. Then it renders the javascript into a div on the page. I've tried making it a CDATA block and extra spacing between the jquery and my script.
Help?

I had this same problem, but I managed to get JavaScript to appear in my code by putting a newline after the opening tag.

Different solution that might work in some cases: (the selected answer didn't work for me when I was trying to embed a CodePen example)
add this to your default layout:
<!-- Custom JavaScript files set in YAML front matter -->
{% for js in page.customjs %}
<script async type="text/javascript" src="{{ js }}"></script>
{% endfor %}
In posts where you need some JavaScript files, you can add them in the YAML front matter like so:
---
layout: post
title: Adding custom JavaScript for a specific post
category: posts
customjs:
- http://code.jquery.com/jquery-1.4.2.min.js
- http://yourdomain.com/yourscript.js
---
The async might not be necessary or wanted but you could probably add that as a parameter in customjs. (see YAML front matter for Jekyll and nested lists for details)

I use this code to write JavaScript code in markdown.
just add js after "```" , and you'll have your JavaScript code highlighted.
```js
const myvar = "hello"
module.exports.response = response = ()=>{mycode here}
```

Markdown supports inline XHTML but not Javascript.

The example they give on their site shows an empty <script> tag containing a newline. Maybe that's it?

I found that escaping the closing '>' symbol in both, the opening and closing 'script' tags, will display it correctly, for example:
If you type the follwing:
<script\>... javascript code...</script\>
It will be rendered like this:
<script>... javascript code...</script>
That's just my two cents.

I built an express server with a library called Showdown that converts markdown to HTML, and also will let you use HTML in your markdown file, and this is how I am able to use javascript and also link to my css file.
TOC.md
<script src="/js/toc"></script>
server.js
app.get('/js/toc', (req, res) => {
fs.readFile(path.join(__dirname, 'public', 'js', 'toc.js'), 'utf-8', (err, data) => {
if(err) throw err;
res.set({
'Content-Type': 'text/javascript'
})
res.send(data)
})
})
Or you could do it using express static middleware. You would just need to put your javascript file inside a folder called public.
TOC.md
<script src="/static/js/toc.js"></script>
server.js
app.use('/static', express.static('public'))

You could use pandoc, which handles this input (and javascript generally) just fine.

To my experience, markdown will outpus javascript text as plain text as long as you remove the code formatting that may confuse markdown.
remove comments from javascript, as /* ... */ is translated to < em>
remove the space indent in the front of each line. < p> may be inserted according to your indentation.
Basically what I do is to review the generated html and find out what extra tags are inserted in between my javascript code by markdown. And remove the formatting that generates the extra tag.

A good idea is to have local and cloud js sources separated:
In the post file:
cloudjs:
- //cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.min.js
- //cdnjs.cloudflare.com/ajax/libs/topojson/1.6.9/topojson.min.js
localjs:
- datamaps.world.min.js
- custom.js
In the default file after footer inclusion:
{% for js in page.cloudjs %}
<script type="text/javascript" src="{{ js }}"></script>
{% endfor %}
{% for js in page.localjs %}
<script type="text/javascript" src="{{ "/assets/scripts/" | prepend: site.baseurl | append: js }}"></script>
{% endfor %}

Just indent the first line contains < script > tag.

Related

Where to add Javascritp/JQuery in laravel 7?

I am new to laravel. I have setup a project with Vue and tried to add jquery code in one of the blade page but I am seeing following error in console. Jquery is working fine but the error in console tells that I am not doing it the right way.
Vue warn]: Error compiling template:
Templates should only be responsible for mapping the state to the UI. Avoid placing tags with side-effects in your templates, such as , as they will not be parsed.
331|
332|
333|
| ^^^^^^^^
334| function refresh(value)
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
335| {
| ^^^^^^^^^
336| location.replace('jiras?status='+value);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
337| }
Can anyone help me that where should I add jquery/javascript code so that it doesn't show any error in the console.
#extends('layout.app')
#section('content')
<your-vue-component></your-vue-component>
#endsection
and inside layout/app.blade.php you can put jquery. Probably above the app.js file
Thank you for your answer Daud.
I created a jquery.js file and added my code inside it. I put this file under public/js/ directory and add the path of it inside app.blade.php file as follows:
<script src="{{ asset('js/jquery.js') }}" defer></script>
The jquery worked fine console error is also gone. Thank you for your help.

Javascript rendering in tornado webserver

In following code snippet I'm trying to add JavaScript Files from Tornado server in HTML file in <HEAD> tag.
DEBUG_SCRIPTS = ''' <script src="src/main.js" type="text/javascript"></script> '''
class Entries(tornado.web.UIModule):
def javascript_files(self):
return 'src/main.js'
class MainHandler(tornado.web.RequestHandler):
def get(self):
params = {}
params['CORE_SCRIPTS'] = DEBUG_SCRIPTS
path = os.path.join(os.path.dirname(__file__), 'index.html')
self.render(path, params=params)
by params['CORE_SCRIPTS'] = DEBUG_SCRIPTS I was trying to add the <script> tag in HTML but it gets parsed in text which generates
<script type="text/javascript" src="src/main.js"></script>
So I came across javascript_files() method in tornado specs but I'm not getting any examples about its implementations. Can anyone help?
javascript files only works with UIModules. Javascript files included that way are appended to the page just before the end of the body tag, though, not in the head tag.
If you really want the file included in the head tag, you can simply output the value of params['CORE_SCRIPTS'] in the head tag of your template:
{% raw params['CORE_SCRIPTS'] %}

Referencing javascript from trac wiki

I have a problem running javascripts from trac.
I know there are security issues around this, but my trac installation is only used as an intranet.
I have got the following code to work (requires setting rendering_unsafe_content = true under [wiki] in trac.ini):
{{{
#!html
<script type="text/javascript" >
document.write("This is a test")
</script>
}}}
However, replacing this with the javascript in a seperate file will fail:
{{{
#!html
<script type="text/javascript" src="/tracproject/htdocs/test.js" >
</script>
}}}
where tracproject is the root folder of trac and test.js contains document.write("This is a test").
Any clues?
Have you tried the 'Add Headers Plugin' (http://trac-hacks.org/wiki/AddHeadersPlugin) ? It looks like it allows you to do include custom javascript like you want but in a more straightforward way than having to modify templates directly.
The option is [wiki] render_unsafe_content (see documentation). You can reference the file in your site htdocs directory on the path /tracproject/chrome/site/test.js. I tried your example just now and it work correctly once the src path is changed.
See the TracInterfaceCustomization page for more details.

smarty assign to javascript external

here in index.tpl
here in javas.js
var currentTS = "{literal}{$userid}{/literal}";
alert(currentTS);
but there will be alert {literal}{$userid}{/literal} not the $userid.
any idea?
Smarty only works under php, you can't run it in .js , unless you add .js to php extensions in apache configruations.
On top of that it seems to me that you are trying to access the {$userid} variable from your index.php. That is never gonna happen! unless you include the file server side like karvonen explained.
And your {literal} tags are unnecessary you start literal when you are gonna use { and } that are not smarty tags but for javascript, css, etc..
and the only time you see them around smarty tags is the other way around as karvonen explained
here's my suggestion: in your index.tpl right before including the java.js file do this:
<!--index.tpl-->
<script type='text/javascript'>UserID = '{$userid}';</script>
<script type='text/javascript' src='pathto/java.js'></script>
/*java.js*/
var currentTS = UserID;
alert(currentTS);
Include the javascript file in your index.tpl. If you have it outside your template directory you must use the file:/... notation (and use your own path, of cours):
<html>
<head
<script type='text/javascript'>
{include file='file:/home/www/mydomain/public_html/js/javas.js'}
</script>
if you have it in your template diretory simply:
<html>
<head
<script type='text/javascriptä>
{include file='javas.js'}
</script>
Now Smarty should parse and compile it.
Moreover, it seems to me that you {literal}{/literal} are the wrong way around. If you are using curly braces in your js file you should start the js with a {literal} tag and "unliteralize" the smarty variables:
{literal}
function test() {
var name = '{/literal}{$name}{literal}';
// do something
}
{/literal}
Don't use {literal}
You don't need it here.
{literal} forces to display all { as they are and don't parse smarty code. Therefore {$userid} will be displayed, as it is.
There is no point in displaying it at the place you are.

Relative Paths in Javascript in an external file

So I'm running this javascript, and everything works fine, except the paths to the background image. It works on my local ASP.NET Dev environment, but it does NOT work when deployed to a server in a virtual directory.
This is in an external .js file, folder structure is
Site/Content/style.css
Site/Scripts/myjsfile.js
Site/Images/filters_expand.jpg
Site/Images/filters_colapse.jpg
then this is where the js file is included from
Site/Views/ProductList/Index.aspx
$("#toggle").click(function() {
if (left.width() > 0) {
AnimateNav(left, right, 0);
$(this).css("background", "url('../Images/filters_expand.jpg')");
}
else {
AnimateNav(left, right, 170);
$(this).css("background", "url('../Images/filters_collapse.jpg')");
}
});
I've tried using '/Images/filters_collapse.jpg' and that doesn't work either; however, it seems to work on the server if I use '../../Images/filters_collapse.jpg'.
Basically, I want have the same functionallity as the ASP.NET tilda -- ~.
update
Are paths in external .js files relative to the Page they are included in, or the actual location of the .js file?
JavaScript file paths
When in script, paths are relative to displayed page
to make things easier you can print out a simple js declaration like this and using this variable all across your scripts:
Solution, which was employed on StackOverflow around Feb 2010:
<script type="text/javascript">
var imagePath = 'http://sstatic.net/so/img/';
</script>
If you were visiting this page around 2010 you could just have a look at StackOverflow's html source, you could find this badass one-liner [formatted to 3 lines :) ] in the <head /> section
get the location of your javascript file during run time using jQuery by parsing the DOM for the 'src' attribute that referred it:
var jsFileLocation = $('script[src*=example]').attr('src'); // the js file path
jsFileLocation = jsFileLocation.replace('example.js', ''); // the js folder path
(assuming your javascript file is named 'example.js')
A proper solution is using a css class instead of writing src in js file.
For example instead of using:
$(this).css("background", "url('../Images/filters_collapse.jpg')");
use:
$(this).addClass("xxx");
and in a css file that is loaded in the page write:
.xxx {
background-image:url('../Images/filters_collapse.jpg');
}
Good question.
When in a CSS file, URLs will be relative to the CSS file.
When writing properties using JavaScript, URLs should always be relative to the page (the main resource requested).
There is no tilde functionality built-in in JS that I know of. The usual way would be to define a JavaScript variable specifying the base path:
<script type="text/javascript">
directory_root = "http://www.example.com/resources";
</script>
and to reference that root whenever you assign URLs dynamically.
For the MVC4 app I am working on, I put a script element in _Layout.cshtml and created a global variable for the path required, like so:
<body>
<script>
var templatesPath = "#Url.Content("~/Templates/")";
</script>
<div class="page">
<div id="header">
<span id="title">
</span>
</div>
<div id="main">
#RenderBody()
</div>
<div id="footer">
<span></span>
</div>
</div>
I used pekka's pattern.
I think yet another pattern.
<script src="<% = Url.Content("~/Site/Scripts/myjsfile.js") %>?root=<% = Page.ResolveUrl("~/Site/images") %>">
and parsed querystring in myjsfile.js.
Plugins | jQuery Plugins
Please use the following syntax to enjoy the luxury of asp.net tilda ("~") in javascript
<script src=<%=Page.ResolveUrl("~/MasterPages/assets/js/jquery.js")%>></script>
I found this to work for me.
<script> document.write(unescape('%3Cscript src="' + window.location.protocol + "//" +
window.location.host + "/" + 'js/general.js?ver=2"%3E%3C/script%3E'))</script>
between script tags of course... (I'm not sure why the script tags didn't show up in this post)...
You need to add runat="server" and and to assign an ID for it, then specify the absolute path like this:
<script type="text/javascript" runat="server" id="myID" src="~/js/jquery.jqGrid.js"></script>]
From the codebehind, you can change the src programatically using the ID.
This works well in ASP.NET webforms.
Change the script to
<img src="' + imagePath + 'chevron-large-right-grey.gif" alt="'.....
I have a master page for each directory level and this is in the Page_Init event
Dim vPath As String = ResolveUrl("~/Images/")
Dim SB As New StringBuilder
SB.Append("var imagePath = '" & vPath & "'; ")
ScriptManager.RegisterClientScriptBlock(Me, Me.GetType(), "LoadImagePath", SB.ToString, True)
Now regardless of whether the application is run locally or deployed you get the correct full path
http://localhost:57387/Images/chevron-large-left-blue.png

Categories