MonoRail - How to write JavaScript within .vm page - castle-monorail

I'm using MonoRail and tried to write a tag within a .vm view to write some JavaScript:
<script type="text/javascript">
//<![CDATA[
$j(document).ready(function()
{
$j('#business_parentbusinesstype_id').change(function()
{
$j.ajax({
url:'http://localhost:88/admin/business/GetChildBusinessTypes',
data: { parentId: $j('#business_parentbusinesstype_id').val() },
dataType: 'script'
});
});
});
//]]>
</script>
You would think that this would work since it's an HTML page but it gives me this error:
Unable to process resource 'admin\business\new.vm': Encountered "\r\n url:\'http://localhost:88/admin/business/GetChildBusinessTypes\',\r\n data: { parentId: " at line 7, column 12.
Was expecting:
...
What am I missing?

I'm wondering if nVelocity is seeing the "$j" and trying to find it in the property bag and execute the "ajax" method. If the "$j" is the short-hand for jQuery, try changing it to the full "jQuery" and see if that works.

Monorail uses the $ sign for objects in the Property Bag. Some things you can do is you can either use the longhand(jQuery.someFuntion()), or move the js to its own js file that you then just include in your vm file.

Related

Dynamically add json content with vue-if and other vue attributes

I am working chrome extension which uses vue. I have found that google can take a while to publish updates, so there is some content that I would like to be able to edit with a json that is called by the extension via a $.getJSON https request. So far, that has worked pretty well for getting raw text. But I have problems when I try to add a span tag with a v-if statement such as the following:
Thank you for meeting. We have prepared the following <span v-if='docCount.length > 0'>documents</span><span v-else>document</span> for you today:
What happens is that it just says "prepared the following 'documentsdDocuments'" as if it takes all to be true.
I have gotten this result after putting the above JSON text in a v-html as follows:
<p v-html="coverLetterContent['p1']"></p>
I have gotten the same result after trying the following:
.bind(this)).then( function (result){
$(".letter-body").append("<p>"+result["letter"]["p1"]+"</p>")
});
I also tried creating a dynamic component as follows but was getting an error and nothing was rendered:
dynamicComponent: function() {
return {
template: `<p>${coverLetterContent["p1"]}</p>`,
methods: {
someAction() {
console.log("Action!");
}
}
}
}
The error I got on this was: "ReferenceError: coverLetterContent is not defined." coverLetterContent is defined in the vue app data and is accessible via the v-html call described above.

Custom widget js doesn't recognize template from qweb

I try to test custom widget from js reference and I get error in debugger:
Error: QWeb2: Template 'some.template' not found
qweb.xml was properly set in manifest, because when I extend ListController and use another template, it works correctly.
Here is template definition, which I use in qweb.xml:
<?xml version="1.0" encoding="UTF-8"?>
<template>
<div t-name="some.template">
<span class="val"><t t-esc="widget.count"/></span>
<button>Increment</button>
</div>
</template>
I tried to change <template> -> <templates>, totally removed tag "template" but still get the same error message.
JS:
odoo.define('working.test', function (require) {
var Widget = require('web.Widget');
var Counter = Widget.extend({
template: 'some.template',
events: {
'click button': '_onClick',
},
init: function (parent, value) {
this._super(parent);
this.count = value;
},
_onClick: function () {
this.count++;
this.$('.val').text(this.count);
},
});
// Create the instance
var counter = new Counter(this, 4);
// Render and insert into DOM
counter.appendTo(".o_nocontent_help");
})
Manifest:
# -*- coding: utf-8 -*-
{
'name': "testwidget",
'summary': """
Short (1 phrase/line) summary of the module's purpose, used as
subtitle on modules listing or apps.openerp.com""",
'description': """
Long description of module's purpose
""",
'author': "My Company",
'website': "http://www.yourcompany.com",
# Categories can be used to filter modules in modules listing
# Check https://github.com/odoo/odoo/blob/12.0/odoo/addons/base/data/ir_module_category_data.xml
# for the full list
'category': 'Uncategorized',
'version': '0.1',
# any module necessary for this one to work correctly
'depends': ['base'],
'qweb': ['static/qweb.xml'],
# always loaded
'data': [
# 'security/ir.model.access.csv',
'views/views.xml',
'views/web_asset.xml',
],
# only loaded in demonstration mode
'demo': [
'demo/demo.xml',
],
}
Any idea how I need to modify this template to make the widget working correctly and in which table in db odoo stores these templates?
I was running into this same issue and needed to put my QWeb code into static/src/xml/base.xml in order for Odoo to recognize it.
You can check to see if Odoo is loading the QWeb by going to this URL on your Odoo instance:
<odoo_instance>/web/webclient/qweb?mods=<my_module_name>
Such as:
localhost:8069/web/webclient/qweb?mods=test
For comparison, you can see a successful output by using mods=web to load the QWeb assets for the web module.
You can try changing
'qweb': ['static/qweb.xml'],
to
'qweb': ['static/*.xml'],
It happens with me sometimes, by specifying static xml file name, it does not render that template. But by just loading all .xml files by using *, templates are loaded.
To solve this issue I used as workaround Widget.xmlDependencies:
xmlDependencies: ['/test/static/qweb.xml']
but the main reason I think was cache in PyCharm which I didn't invalidate.
After having done some code reading, IMO, I realized the official documentation might not have pointed out clearly how to use templates in frontend.
To summarize my understanding:
The 'qweb' field in manifest is mainly designed for webclient (i.e. the backoffice), not the website. When entering webclient, a request to /web/webclient/qweb is made to retrieve all the templates of installed modules.
In order to use templates in website (i.e. frontend), synchronous and asynchronous ways both exist.
Synchronous way: Use qweb.add_template. When parameter is template content itself or a DOM node, template is loaded in a synchronous way. (While param is a URL, then it fires up an ajax request to server to fetch content.)
qweb.add_template is mentioned in https://www.odoo.com/documentation/13.0/reference/qweb.html
Asynchronous way:
Use ajax.loadXML which you can use anywhere you want to start loading template from a URL.
Use xmlDependencies which you specify in widget definition. And if you dig into the code in widget.js, you can see ajax.loadXML is being used in willStart.
There are discussions regarding qweb.add_template vs ajax.loadXML
See https://github.com/OCA/pylint-odoo/issues/186 and https://github.com/odoo/odoo/issues/20821
FYI.
I guess you may need to make sure that the js definition refers to the module name correctly
odoo.define('MODULE TECHNICAL NAME SHOULD BE HERE.test', function (require) {});
you should also register your js function with something like:
core.action_registry.add("module_name.name", Widget_Extend);
for more info https://www.odoo.com/documentation/11.0/reference/javascript_reference.html#registries
In Odoo 14 make sure
dashboard.js
odoo.define('library_managment.dashboard', function(require) {
"use strict";
// alert("hello odoo...............")
console.log("Hello My Module........!!")
var widgetRegistry = require('web.widget_registry');
var Widget = require('web.Widget');
var Counter = Widget.extend({
template: 'library_managment.template',
xmlDependencies: ['/library_managment/static/src/xml/template.xml'],
events: {
'click button': '_onClick',
},
init: function (parent, value) {
this._super(parent);
this.count = 4*9+5;
console.log("parent is", parent)
console.log("counter is..", this.count)
},
_onClick: function () {
this.count++;
this.$('.val').text(this.count);
},
});
widgetRegistry.add('library_counter', Counter);
return Counter;
});
template.xml
add this
<?xml version="1.0" encoding="UTF-8"?>
<odoo>
<div t-name="library_managment.template">
<span class="val">
<t t-esc="widget.count"/>
</span>
<button class="bg-danger">Increment</button>
</div>
</odoo>
then add js file in assets.xml inside youe views
<odoo>
<template id="assets_backend" name="Library assets" inherit_id="web.assets_backend">
<xpath expr="." position="inside">
<script type="text/javascript" src="/library_managment/static/src/js/dashboard.js"></script>
</xpath>
</template>
</odoo>
then add in manifest like this:
'js': ['/static/src/js/dashboard.js'],
'qweb': ['/static/src/xml/template.xml']
then inside form view add this line
<widget="library_counter"/>
I had the same problem but with "hr_org_chart" template idk why everything works fine in another computer but in mine it returned this problem, I solved it by installing this module hr-org-chart

angular-translate is not translating with loaded static file

I'm using the following angular files for translations:
angular-translate.min.js (v2.2.0)
angular-translate-loader-static-files.min.js (v2.2.0)
angular-translate-storage-cookie.min.js (v2.2.0 )
angular-translate-storage-local.min.js (v2.2.0)
angular-cookies.min.js (v1.2.22)
angular-translate works when I do the following:
$translateProvider.translations('en_us', {
"label.test": "It works."
});
But not when I attempt to use a static file...
My HTML:
<html data-ng-app="myApp">
...
{{"label.test" | translate}}
My app.js:
var myApp = angular.module('myApp', ['ngCookies', 'pascalprecht.translate']).config(['$translateProvider', function($translateProvider) {
$translateProvider.preferredLanguage('en_us');
$translateProvider.useStaticFilesLoader({
prefix: '/app/resources/messages/i18n_',
suffix: '.json'
});
$translateProvider.useLocalStorage();
$translateProvider.storageKey('lang');
}]);
My Get Response (with Content-Type set to: application/json):
{
"label.test":"It works from JSON."
};
The rendered HTML page shows: label.test
Additionally, there are no errors in my console. I also tried renaming the key to TEST, but that didn't work, either.
Any ideas?
Thanks.
Check that the path to your .json is correct. If it is not found, in your template, it will just print out label.test instead of the actual translation It works from JSON. just like it is doing.
Your app root is most likely app, so if your translation file is located in /app/resources/messages/i18n_en_us.json then try:
$translateProvider.useStaticFilesLoader({
prefix: '/resources/messages/i18n_',
suffix: '.json'
});
Also make sure your JSON is valid JSON. Remove the semi-colon at the end.
{
"label.test":"It works from JSON."
}

Problems interning strings for custom Dojo build

Trying to figure out why I can't seem to intern strings in my dojo build. My layer files get created correctly, but the code associated with each of the individual dijits doesn't get interned properly.
Here is a piece of portion of the build output that illustrates where it is failing:
release: Interning strings for : ../../release/fwijits5.31.2012/content/fwijits/optionalDijits/commenting.js
release: ../../release/fwijits5.31.2012/content/fwijits/optionalDijits/templates/commenting.htm
release: Optimizing (shrinksafe, stripConsole=normal) file: ../../release/fwijits5.31.2012/content/fwijits/optionalDijits/commenting.js
release: Could not strip comments for file: ../../release/fwijits5.31.2012/content/fwijits/optionalDijits/commenting.js,
error: InternalError: illegal character
It looks like the optimize fails because the template doesn't get added to the js file properly. Here is what the js looks like after the html gets interned. You can't tell from the output, but a byunch of special characters get tacked on at the end of the javascript.
if(!dojo._hasResource["fwijits.optionalDijits.commenting"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["fwijits.optionalDijits.commenting"] = true;
dojo.provide("fwijits.optionalDijits.commenting");
dojo.require("dijit._Widget");
dojo.require("dijit._Templated");
dojo.require("dijit.layout.ContentPane");
dojo.require("dijit.layout.TabContainer");
//The main widget that gets returned to the browser
dojo.declare("fwijits.optionalDijits.commenting", [dijit.layout.ContentPane, dijit._Templated], {
widgetsInTemplate: true,
_earlyTemplatedStartup: true,
templateString: dojo.cache("fwijits.optionalDijits", "templates/commenting.htm"),
basePath: dojo.moduleUrl("fwijits.optionalDijits"),
//This function contains all configurable parameters
constructor: function(params){
params = params ||{};
this.inherited(arguments);
},
//This functions run on a "startup" call
startup: function(){
var _this = this;
this.inherited(arguments);
},
_addPointComment:function(){
console.debug("button clicked");
}
});
}
The htm file is pretty simple, so I don't think it's the root of my problem.
<div dojoAttachPoint="containerNode">
<div dojoattachpoint="_outerDiv">
<div dojoattachpoint="_addPoint" dojotype="dijit.form.Button" dojoattachevent="onClick:_addPointComment"><b>Add Comment</b></div>
</div>
</div>
Any suggestions?
Which version of Dojo? There is a bug in the build system with interning strings that do not end in HTML or HTM, although I've never tried with HTM to know for sure.
Might be worth a check. I know this was fixed in 1.7 and backported to 1.8.
https://bugs.dojotoolkit.org/ticket/15867

Chrome Extensions and loading external Google APIs Uncaught ReferenceError

Right now I'm in the process of creating a Chrome extension. For it, I need to use Google's Calendar Data API. Here is my manifest.json file:
{
"name": "Test",
"version": "1.0",
"background_page": "background.html",
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["jquery.js", "content_script.js"]
}
],
"permissions": [
"tabs", "http://*/*"
]
}
I've tried adding the following to the js part of the manifest file but that throws an error when loading the extension.
http://www.google.com/jsapi?key=keyhere
I've also tried adding
document.write('<script type="text/javascript" src="http://www.google.com/jsapi?key=keyhere"></script>');
to my background.html file. However, whenever I call
google.load("gdata", "1");
I get an error that says Uncaught ReferenceError: google is not defined. Why is my extension not loading this api when it loads the other ones fine?
You can't include external script into content_scripts.
If you want to inject <script> tag using document.write then you need to mask slash in a closing tag:
document.write('...<\/script>');
You can include your external api js into background page just as usual though:
<script type="text/javascript" src="http://www.google.com/jsapi?key=keyhere"></script>
If you need this api in content scripts then you can send a request to your background page and ask it to do API-dependent stuff there, and then send a result back to your content script.
Thanks for that link, it helped a lot. However, now I've run into another interesting problem.
for (var i = rangeArray.length - 1; i >= 0; i--) {
var myLink = document.createElement('a');
myLink.setAttribute('onclick','helloThere();');
myLink.innerText ="GO";
rangeArray[i].insertNode(myLink);
}
Now I get the error, "helloThere is not defined" even though I placed that function about ten lines above the current function that has the above loop in the same file. Why might this be happening? And if I do:
for (var i = rangeArray.length - 1; i >= 0; i--) {
var myLink = document.createElement('a');
myLink.setAttribute('onclick','chrome.extension.sendRequest({greeting: "hello"}, function(response) { });');
myLink.innerText ="GO";
rangeArray[i].insertNode(myLink);
}
I get Uncaught TypeError: Cannot call method 'sendRequest' of undefined
This is because there is some syntax error in your code. I had same problem. I opened my background.html page in fire fox with fire-bug plug-in enabled. Fire-bug console should me the error, I fixed and it is working now.