During the work on some Freestyle UI5 Apps I always look for a way how to save constants in Frontend. I would like to share following practice with you, which I use currently.
Define JSON File with Constants
I am going to create a new File in my project root folder. In this file all constant and values will be stored as a JSON Object.
/webapp/model/constants.json
1 2 3 4 5 6 |
{ "ConstantString": "Hello World", "ConstantInt": 123 } |
Define JSON Model in manifest.json file
I my project manifest.json, I am going to define a new JSON Model with created JSON file in URI
1 2 3 4 5 6 7 8 9 10 11 12 |
"models": { "i18n": { ... }, "constants": { "type": "sap.ui.model.json.JSONModel", "uri": "model/constants.json" }, "": { ... } } |
Using Constants in View
From now on it is possible to use the constant model in View:
1 2 3 4 5 6 7 |
... <Page id="page" title="Cadaxo UI5 Snippets #1"> <content> <Text text="{constants>/ConstantString}" /> </content> </Page> ... |
Using Constants in Controller
And of course also in Controllers. For example like this:
1 2 3 4 5 6 7 8 |
... onInit: function () { const oView = this.getView(); const oModel = oView.getModel("constants"); const iConstantInt = oModel.getProperty("/ConstantInt"); } ... |
Let me know how you save constants in Frontend or leave a comment if you found this blog post useful!