i want to add a reference to my scripts in a Laravel app. In my edit UI I have the reference like this:
{{ HTML::script('js/exam-definition.js') }}
{{ HTML::script('js/exam-definition-update.js')}}
The scrpits are in the folder: /public/js/exam-definition.js and the same for the other. But when I deploy in the browser the page give me this error:
http://test.dev/public/exam/js/exam-definition.js?=1406161079799
http://test.dev/public/exam/js/messages.js?=1406161079800
You can see how the URL changes (because asset take), append an "exam" folder that dont exists. Is something wrong? I have this same ref to the scripts in another blade template and there is no error when deploy.
This are my controller method:
/**
* Show the form for edit a Exam
*/
public function edit($id) {
$exam = ExamService::examDefinition($id);
$questions = $exam->getQuestions()->getResults();
return View::make('exam.edit')
->with('exam', $exam)
->with('questions', $questions);
}
And the route for this page:
Route::get('exam/edit/{id}',
array('as' => 'exam_edit',
'uses' => 'ExamDefinitionController#edit'
)
);
Thanks in advance!
You should use
{{ HTML::script('/js/exam-definition.js') }}
{{ HTML::script('/js/exam-definition-update.js')}}
This will create a reference starting from the web root, and not from your current directory where the file is at. This also explains why your code could work from another blade template.
Related
I have used this section of code in layout section of my Laravel project:
#php
$setting = setting();
#endphp
As it is a layout I didn't call this file anywhere but included it many times.
And wherever it is included it is showing me this error.
Error
Call to undefined function setting()
What went wrong here?
my setting model is:
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class Setting extends Model
{
protected $table = 'setting';
protected $primaryKey = 'id';
}
?>
also my full layout file is Here
setting function is defined in the Helper.php file. here it is:
<?php
function setting(){
return \App\Model\Setting::first();
}
?>
how can I fix this? TIA
you don't need to use :
#php
$setting = setting();
#endphp
the composer has a files key (which is an array of file paths) that you can define inside of autoload. so you can add the path of the helpers file in the composer.json file:
"autoload": {
"psr-4": {
"App\\": "app/"
},
"classmap": [
"database/seeds",
"database/factories"
],
"files": [
"app/Helpers.php"
]
},
then Run :
composer dump-autoload
after that in your layout you can use {{setting()->email}} or if you use $setting =setting(); in your layout use {{$setting->email}}
Assuming your Manager is properly configured and eloquent booted.
Your file does not get included via composers autoload. But you actually dont need to load it.
#php
$setting = \App\Model\Setting::first();
#endphp
I know this question maybe exist in stack overflow but I didn't get any good answers, and I hope in 2020 there is better solution.
In my react app I have a config JSON file, it contains information like the title, languages to the website etc..
and this file is located in 'src' directory
{
"headers":{
"title":"chat ",
"keys":"chat,asd ,
"description":" website"
},
"languages":{
"ru":"russian",
"ar":"arabic",
"en":"English"
},
"defaultLanguage":"ru",
"colors":{
"mainColor":"red",
"primary":"green",
"chatBackGround":"white"
}
}
I want to make my website easy to edit after publishing it, but after I build my app, I can't find that settings.json file there in build directory.
I find out that files in public directory actually get included to build folder, I tried to put my settings.JSON in public,
but react won't let me import anything outside of src directory
I found other solutions like this one but didn't work
https://github.com/facebook/create-react-app/issues/5378
Also I tried to create in index.html a global var like (window.JSON_DATA={}), and attach a JS object to it and import it to App.js, but still didn't work.
How can I make a settings JSON file, and have the ability to edit it after publishing the app?
Add your settings.json to the public folder. React will copy the file to the root of build. Then load it with fetch where you need it to be used. For example if you need to load setting.json to the App.js then do the next:
function App() {
const [state, setState] = useState({settings: null});
useEffect(()=>{
fetch('settings.json').then(response => {
response.json().then(settings => {
// instead of setting state you can use it any other way
setState({settings: settings});
})
})
})
}
If you use class-components then do the same in componentDidMount:
class CustomComponent extends React.Component {
constructor(props) {
super(props);
this.state = {settings: null};
}
componentDidMount() {
fetch('settings.json').then(response => {
response.json().then(settings => {
this.setState({settings: settings});
})
})
}
}
Then you can use it in render (or any other places of your component):
function App() {
...
return (
{this.state.settings && this.state.settings.value}
)
}
The easiest way would be to require() the file on the server during server side rendering of the html page and then inline the json in the html payload in a global var like you mentioned window.JSON_DATA={}. Then in your js code you can just reference that global var instead of trying to use import.
Of course this approach would require you to restart your server every time you make a change to the json file, so that it get's picked up. If that is not an option then you'll need to make an api call on the server instead of using require().
You may want to look at using npm react-scripts (https://www.npmjs.com/package/react-scripts) to produce your react application and build. This will package will create a template that you can put your existing code into and then give you a pre-configure build option that you can modify if you would like. The pre-configured build option will package your .json files as well. Check out their getting started section (https://create-react-app.dev/docs/getting-started/)
If you don't want to go that route, and are just looking for quick fix, then I would suggest change your json files to a JS file, export the JS object and import it in the files you need it since you seem to be able to do that.
//src/sampledata.js
module.exports = {
sample: 'data'
}
//src/example.jsx (this can also be .js)
const sampledata = require('./sampledata');
console.log(sampledata.sample); // 'data'
you can use 'Fetch Data from a JSON File'
according to link
https://www.pluralsight.com/guides/fetch-data-from-a-json-file-in-a-react-app
example
I registered it
handlebars.registerPartial('nav', 'view/partials/nav');
And I called it
{{> "nav"}}
but I only get this
view/partials/nav
According to documentation arguments of .registerPartial(arg1, arg2) are:
Partial name
Partial content
Handlebars does not have built in functionality to serve static files from relative paths.
So without using external framework like for example the one hapijs uses to render views, what you can do is:
Handlebars.registerPartial('nav',
('<nav>' +
// your <nav> html
// ...
// ...
</nav>')
);
Starting to learn react and couldn't find the answer to this on the internet. Maybe I don't know what terms to use.
My backend is django and I want to be able to pass in URLs for REST APIs to my React front end.
I don't want to hard code them in react as they are already defined in django.
It makes sense to me that I would want to render a script tag on my html template that contains an object containing the URL values.
e.g. the django template would have something like
<script type="text/javascript">
var CONFIG = {
some_url : '{% url "my-api" %}'
}
</script>
(for those not familiar with django, that {% url %} tag renders a url like /path/to/myapi)
Then in my React Stores/Actions I would just refer to CONFIG.some_url.
Is this the right way to do it? Or is there a better way to make this information available to my react components.
------------ Edit -----------------
Using webpack to transpile the jsx files and using django-webpack-loader to integrate everything. this means that the django templates are completely rendered before the jsx is loaded on top.
As a result the template tags cannnot run inside the jsx files.
Even though you're using django-webpack-loader(I am too), you still can pass props to your React app. You can proceed like this:
1) Resolve the absolute backend url in your view.py:
def get_context_data(self, **kwargs):
context['APIROOT_URL'] = reverse('api-root', request=self.request)
return context
2) Pass the context prop to the html template
<div id="react-app"></div>
<script>
window.__APIROOT_URL__= '{{ APIROOT_URL }}';
window.react_mount = document.getElementById('react-app');
</script>
{% render_bundle 'main' %}
3) Finally inside your app, get the property like this:
const apirootUrl = window.__APIROOT_URL__
pass it as props:
<MyComponent src={% url %} />
Put following plugin in your webpack configuration:-
plugins: [
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify(process.env.environ),
}
})
],
Run the webpack command as follows:-
environ=local webpack
or
environ=production webpack -p //for production
Create a constants file where you keep a function which returns API
urls based on environment variable set above.(local,dev,production).
const api_url=function(){
let api_url=//production api url
if(process.env.NODE_ENV == 'local'){
//local api url
}
else if(process.env.NODE_ENV == 'development'){
//dev api url
}
return api_url;
}
export const url= api_url();
Import this in your componentDidMount() call the api using ajax/fetch/axios
import {url} from ../constants
componentDidMount(){
//api call
}
If you are using django and react together I would strongly suggest to look at django-webpack-loader once
I have a project that accesses profile images dynamically from JSON retrieved from an API service. The problem is I'm having a tough time figuring out where in the file system to put these images during development and what the path should be in the JSON.
Here is a small example:
<template>
<li :class="{'is-active': isActive}">
<div class="responsible">
<profile-picture :the-url="user.profilePicture" the-size="large"></profile-picture>
{{ user.name }}
</div>
</li>
</template>
<script>
import ProfilePicture from '../components/ProfilePicture'
export default {
data () {
return {
isActive: false
}
},
props: [
'user'
],
components: {
'profile-picture': ProfilePicture
}
}
</script>
So, what would be the path that user.profilePicture should have and where should that file be located in the filesystem? Again, I don't want to pack the image with webpack - I want this to come from a library of images that users have uploaded. Any help is appreciated!
They can go anywhere in your publicly visible folder (the one with index.html in it). Then you just make the path relative to that, so if you put them in public/images/users the path would be /images/users/filename.png.
You could also have the ProfilePicture component handle the path, and just store the filename in your database. So the database would store filename.png and your ProfilePicture component would know to add /images/users/ to the beginning. That way if you change the profile picture folder later you don't have to update DB records, just change the ProfilePicture component. This is probably best.