In this simple example: https://jsfiddle.net/4hxsu4rc/2/
Is it possible to place the @Content.myVarIntoJsFile inside the js file that is included via <script src="myjs.js"></script>
?
Since it is not part of the view template associated file (_myview.cshtml), it does not work by default.
The only way I can make this work is by having the whole JS content inside the _myview.cshtml like
<script type="text/javascript">
function myfunction(myvalue) {
alert('@Content.myVarIntoJsFile' + myvalue);
}
</script>
but this makes the view template file harder to edit since the size will be considerable. How can I use @Content.field replacements in external JS files?
Best regards, João
There are a few options :)
What @joecraig was suggesting, is to use a system like
<div data-name="@Content.Name" data-age="@Content.Age">...</div>
to transport your data in html, for use in your javascript. This works well for simple use cases, and allows you to put your "business" logic in separate JS files.
The Pro-method is to use WebAPIs, get JSON-streams of the data you need, and have fun. Basically all 2sxc-data is easily available as json if you want it. To give you a perfect answer, I would need to know what JS-framework you're using.
For example, if you're using jQuery, then something like this will get you all items of type "Category"
var sxc = $2sxc(someTagInsideYourModule);
var dataPromise = sxc.webApi.get("app/auto/content/Category");
dataPromise.then(function(result) { /* do something */ });
You can read more about this on https://github.com/2sic/2sxc/wiki/WebApi
If you're using other frameworks - like AngularJS, there are helpers like the Query-Service or Content-Service.
PS: remember to enable read-permissions for the non-admin users, otherwise the code will only work when logged in.