如何制作营养膳食计算器_如何创建随机膳食生成器
如何制作營養膳食計算器
Last week I decided to take on a new challenge. I called it: The #100Days100Projects Challenge.
上周,我決定接受一個新的挑戰。 我稱之為: #100Days100Projects挑戰。
The purpose of the challenge is to create one project every single day. Think of it as a next step for the #100DaysOfCode challenge.
挑戰的目的是每天創建一個項目。 將其視為#100DaysOfCode挑戰的下一步。
A project can be either:
一個項目可以是:
- an app 一個應用
- a component 一個組件
- a website 一個網站
- a game 一個游戲
a library
圖書館
and so on...
等等...
The programming language used is also not important, but I need to complete the project by 11:59 PM (my time), otherwise I'm "punishing" myself by giving away $5 for 5 people ($25 total) - first 5 people who point it out on Twitter that I missed the deadline. 😄
所使用的編程語言也不重要,但是我需要在11:59 PM(我的時間)之前完成該項目,否則我將通過“懲罰”我的方式,即每5人贈送5美元(總計25美元)-前5個人在Twitter上指出我錯過了截止日期。 😄
If you want to join, you can read more about this challenge and the other variants it has here.
如果您想加入,可以在此處閱讀有關此挑戰及其其他變體的更多信息。
Note: you don't have to give away $5 if you fail, just set some other "punishment" for yourself. Also, there are other variants with less days (7Days7Projects and 30Days30Projects) if you don't feel like taking on the 100Days challenge.
注意 :如果失敗,您不必捐出$ 5,只需為自己設置其他“懲罰”即可。 另外,如果您不想參加100Days挑戰,那么還有其他幾天的變體會更少( 7Days7Projects和30Days30Projects )。
For the first project in the #100Days100Projects I thought about working with a public API in order to get some data that would be displayed in a webpage - an usual thing to do with an API.
對于#100Days100Projects中的第一個項目,我考慮過使用公共API來獲取一些可以在網頁上顯示的數據-這是與API共同的事情。
For that I chose to use TheMealDB's public API in order to get some random meals by pressing a button. Something straightforward! 😄
為此,我選擇使用TheMealDB的公共API,以便通過按一下按鈕獲得一些隨機食物。 簡單明了! 😄
Check out the live version of what we're going to build in this article over on CodePen:
在CodePen上查看我們將在本文中構建的實時版本:
As always let's start at the beginning:
與往常一樣,讓我們??從頭開始:
HTML (The HTML)
<div class="container"><div class="row text-center"><h3>Feeling hungry?</h3><h5>Get a random meal by clicking below</h5><button class="button-primary" id="get_meal">Get Meal 🍔</button></div><div id="meal" class="row meal"></div> </div>We have a little text, but the two most important parts are:
我們有一點文字,但是兩個最重要的部分是:
the #get_meal button and
#get_meal按鈕和
the #meal div
#meal div
We're going to use the button to make a request to the API. This will send back some data that we're going to put into the #meal div which acts as a container - in this case.
我們將使用button向API發出請求。 這將發回一些數據,我們將把它們放入用作容器的#meal div中(在這種情況下)。
Usually after the HTML I'll go right into the CSS. But we don't yet have the entire markup as it will be populated in the JavaScript section, so that's what we're going to do next.
通常在HTML之后,我會直接進入CSS。 但是我們還沒有完整的標記,因為它將在JavaScript部分中進行填充,所以這就是我們下一步要做的。
JavaScript (The JavaScript)
As mentioned above, we need the button and that container div:
如上所述,我們需要button和那個容器div :
const get_meal_btn = document.getElementById('get_meal'); const meal_container = document.getElementById('meal');Next, before we dive more into the code, let's see what the API is going to return. For that please open the following URL: https://www.themealdb.com/api/json/v1/1/random.php.
接下來,在深入研究代碼之前,讓我們看看API將會返回什么。 為此,請打開以下URL: https : //www.themealdb.com/api/json/v1/1/random.php 。
As you can see from the URL, we are getting a random meal from this API (refresh to see the randomness). When we're making a GET request to that endpoint (like accessing it from the browser), it sends back a JSON response, which we can parse in order to retrieve the data we want.
正如您從URL中看到的那樣,我們從此API中獲得了隨機餐點(刷新以查看隨機性 )。 當我們向該端點發出GET請求(例如從瀏覽器訪問它)時,它將發送回JSON響應,我們可以對其進行解析以檢索所需的數據。
The data looks something like this:
數據看起來像這樣:
{meals: [{idMeal: '52873',strMeal: 'Beef Dumpling Stew',strDrinkAlternate: null,strCategory: 'Beef',strArea: 'British',strInstructions: 'Long description',strMealThumb:'https://www.themealdb.com/images/media/meals/uyqrrv1511553350.jpg',strTags: 'Stew,Baking',strYoutube: 'https://www.youtube.com/watch?v=6NgheY-r5t0',strIngredient1: 'Olive Oil',strIngredient2: 'Butter',strIngredient3: 'Beef',strIngredient4: 'Plain Flour',strIngredient5: 'Garlic',strIngredient6: 'Onions',strIngredient7: 'Celery',strIngredient8: 'Carrots',strIngredient9: 'Leek',strIngredient10: 'Swede',strIngredient11: 'Red Wine',strIngredient12: 'Beef Stock',strIngredient13: 'Bay Leaf',strIngredient14: 'Thyme',strIngredient15: 'Parsley',strIngredient16: 'Plain Flour',strIngredient17: 'Baking Powder',strIngredient18: 'Suet',strIngredient19: 'Water',strIngredient20: '',strMeasure1: '2 tbs',strMeasure2: '25g',strMeasure3: '750g',strMeasure4: '2 tblsp ',strMeasure5: '2 cloves minced',strMeasure6: '175g',strMeasure7: '150g',strMeasure8: '150g',strMeasure9: '2 chopped',strMeasure10: '200g',strMeasure11: '150ml',strMeasure12: '500g',strMeasure13: '2',strMeasure14: '3 tbs',strMeasure15: '3 tblsp chopped',strMeasure16: '125g',strMeasure17: '1 tsp ',strMeasure18: '60g',strMeasure19: 'Splash',strMeasure20: '',strSource:'https://www.bbc.co.uk/food/recipes/beefstewwithdumpling_87333',dateModified: null}]; }Basically we get back an array of meals, but with only one item in it - the randomly generated one. And this item has all the data we want to showcase in our little application. Things like:
基本上,我們取回一meals ,但其中只有一個-隨機產生的。 并且此項目具有我們要在我們的小應用程序中展示的所有數據。 像:
meal name (under strMeal)
餐名(在strMeal下)
meal caterogy (under strCategory)
膳食分類(在strCategory下)
meal image (under strMealThumb)
膳食圖像(在strMealThumb下)
a youtube video with the recipe (under strYoutube)
帶有配方的youtube視頻(在strYoutube )
the ingredients and the measures (under strIngredientsX and strMeasureX - X representing the nth ingredient and it's measure).This is a little bit awkward as I would expect here to have an array with this information, but they choose to add it as object props. On well... 😃 The important thing to note is that there are a maximum of 20 ingredients / measures, although they aren't all filled in - some of them might be empty so we need to account for that.
成分和度量(在strIngredientsX和strMeasureX下-X代表第n個成分及其度量)。這有點尷尬,因為我希望在這里具有一個包含此信息的數組,但是他們選擇將其添加為對象道具。 好吧...😃要注意的重要一點是,雖然還沒有全部填寫,但最多有20種成分/度量-其中有些可能是空的,因此我們需要對此加以考慮。
Now that we have the button we're going to add an event listener for the click event. Inside we're going to make a request to the API:
現在我們有了按鈕,我們將為click事件添加一個事件偵聽器。 在內部,我們將向API發出請求:
get_meal_btn.addEventListener('click', () => {fetch('https://www.themealdb.com/api/json/v1/1/random.php').then(res => res.json()).then(res => {createMeal(res.meals[0]);}).catch(e => {console.warn(e);}); });We're using the fetch API to do the request. We just have to pass in the url of the API we want to make a GET request to, and we're going to get back a promise.
我們正在使用訪存 API來執行請求。 我們只需要傳遞要發出GET請求的API的URL,我們就可以收回承諾。
Once this is resolved we have a response (res). This res isn't yet in the state we want it to be, so we're going to call the .json() method on it. Then finally we have the beautiful object. Yay! 👏
解決此問題后,我們將做出回應( res )。 此res尚未處于我們想要的狀態,因此我們將對其調用.json()方法。 最后,我們有了美麗的物體。 好極了! 👏
As mentioned above, the API returns the meals array but only with an item in it. So we're going to pass that item (at index 0) into our createMeal function, which we'll define next.
如上所述,API返回的meals數組,但其中僅包含一個項目。 因此,我們將將該項目(在索引0 )傳遞到我們的createMeal函數中,我們將在下面定義它。
I'm going to paste the entire block of code below and we're going to go into detail afterwards, so hold on for a second. 🤓
我將在下面粘貼整個代碼塊,然后再進行詳細介紹,因此請稍等片刻。 🤓
const createMeal = meal => {const ingredients = [];// Get all ingredients from the object. Up to 20for (let i = 1; i <= 20; i++) {if (meal[`strIngredient${i}`]) {ingredients.push(`${meal[`strIngredient${i}`]} - ${meal[`strMeasure${i}`]}`);} else {// Stop if there are no more ingredientsbreak;}}const newInnerHTML = `<div class="row"><div class="columns five"><img src="${meal.strMealThumb}" alt="Meal Image">${meal.strCategory? `<p><strong>Category:</strong> ${meal.strCategory}</p>`: ''}${meal.strArea ? `<p><strong>Area:</strong> ${meal.strArea}</p>` : ''}${meal.strTags? `<p><strong>Tags:</strong> ${meal.strTags.split(',').join(', ')}</p>`: ''}<h5>Ingredients:</h5><ul>${ingredients.map(ingredient => `<li>${ingredient}</li>`).join('')}</ul></div><div class="columns seven"><h4>${meal.strMeal}</h4><p>${meal.strInstructions}</p></div></div>${meal.strYoutube? `<div class="row"><h5>Video Recipe</h5><div class="videoWrapper"><iframe width="420" height="315"src="https://www.youtube.com/embed/${meal.strYoutube.slice(-11)}"></iframe></div></div>`: ''}`;meal_container.innerHTML = newInnerHTML; };Basically the entire function's purpose is to get the JSON response, parse it, and transform it into an HTML component. For that we need to do a couple of things, as the data is not yet formated exactly the way we want it to be.
基本上,整個功能的目的是獲取JSON響應,對其進行解析并將其轉換為HTML組件。 為此,我們需要做幾件事情,因為數據尚未按照我們希望的方式完全格式化。
First, we're getting all the ingredients and their measures. As mentioned above there are a maximum of 20 ingredients, but they are separated into their own properties in the object like: strIngredient1, strIngredient2, etc... (I still don't know why they did that, but... 🙄).
首先,我們要掌握所有要素和措施 。 如上所述,最多有20種成分,但是它們在對象中分成了自己的屬性,例如: strIngredient1 , strIngredient2等(我仍然不知道為什么這樣做,但是...🙄) 。
So, we're creating a for loop which goes from 1 to 20 and checks if the meal has that corresponding ingredient-measure pair. If it does, we're putting it into the ingredients array. If there aren't any more ingredients we're stopping the for loop with a break condition.
因此,我們正在創建一個從1到20的for循環,并檢查meal是否具有相應的ingredient - measure對。 如果是這樣,我們會將其放入ingredients數組。 如果沒有更多的成分,我們將使用break條件停止for循環。
Next, we're creating the newInnerHTML string which is going to hold the entire HTML markup. In it we are parsing the remaining properties that we want to be displayed.
接下來,我們將創建newInnerHTML字符串,該字符串將保留整個HTML標記。 在其中,我們正在解析要顯示的其余屬性。
Note that some of the properties might not be available. So for that we're using the ternary operator to check if we have the data to display the corresponding tag. If we don't have it then we're returning an empty string and nothing will be displayed on the page. The category and the area are examples of these type of properties.
請注意 ,某些屬性可能不可用。 為此,我們使用三元運算符來檢查是否有數據顯示相應的標簽。 如果沒有它,那么我們將返回一個空字符串,并且頁面上將不會顯示任何內容。 category和area是這些類型的屬性的示例。
The tags are coming in a string divided by a comma like: 'tag1,tag2,tag3'. So we need to split it by that comma, and join it back by a comma and a space as it looks nicer ('tag1, tag2, tag3' ??). Or at least for me does. 😅
標簽以字符串形式出現,并用逗號分隔,例如: 'tag1,tag2,tag3' 。 因此,我們需要用逗號split其split ,并用逗號和空格join其重新組合起來,因為它看起來更好( 'tag1, tag2, tag3' tag3'??)。 或者至少對我而言。 😅
To show the ingredients, we're mapping over the array and we're creating an <li> for each ingredient/measure pair. At the end we're joining the array back to form a string. (This is something you would do in ReactJS but without the joining part 😛).
為了顯示ingredients ,我們在數組上進行映射,并為每個成分/度量對創建一個<li> 。 最后,我們將數組重新連接成一個字符串。 (這是你會在ReactJS做,但沒有join荷蘭國際集團的部分😛)。
There is also a Youtube video string (maybe) which is returning the URL of the video. But in order for us to embed the video in the page we need to extract the video ID only. For that we're using .slice(-11) to get the last 11 characters of the string as this is where the ID is hiding 😃.
還有一個YouTube視頻字符串 (也許)正在返回視頻的URL。 但是為了使我們將視頻嵌入頁面,我們只需要提取視頻ID。 為此,我們使用.slice(-11)來獲取字符串的最后11個字符,因為這是ID隱藏的位置。
And finally, we're setting this entire newInnerHTML to be the meal_container's innerHTML -> this will populate that div with all this information!
最后,我們將整個newInnerHTML設置為meal_container的innerHTML >這將使用所有這些信息填充該div!
This entire process will repeat every time we're pressing the Get Meal button.
每當我們按下“ Get Meal按鈕時,整個過程都會重復。
CSS (The CSS)
The last part is to style it a little bit, right? 😉
最后一部分是樣式設置,對嗎? 😉
For the CSS I wanted to use something new so I tried out the SkeletonCSS library. It's useful if you have a small project and don't want to get overwhelmed with all those classes, as it only has a couple of them that take care of some basic styling (the button for example) and the responsive part.
對于CSS,我想使用一些新的東西,所以我嘗試了SkeletonCSS庫。 如果您有一個小型項目,并且不想被所有這些類弄得不知所措,那么它很有用,因為它只有幾個,它們負責一些基本的樣式(例如按鈕)和響應部分。
@import url('https://fonts.googleapis.com/css?family=Muli&display=swap');* {box-sizing: border-box; }body {display: flex;flex-direction: column;justify-content: center;align-items: center;padding: 30px 0;min-height: calc(100vh - 60px); }img {max-width: 100%; }p {margin-bottom: 5px; }h3 {margin: 0; }h5 {margin: 10px 0; }li {margin-bottom: 0; }.meal {margin: 20px 0; }.text-center {text-align: center; }.videoWrapper {position: relative;padding-bottom: 56.25%;padding-top: 25px;height: 0; }.videoWrapper iframe {position: absolute;top: 0;left: 0;width: 100%;height: 100%; }You can see that the CSS is pretty simple. The only part that's worth mentioning is the .videoWrapper CSS declaration. This makes sure that the YouTube embed is responsive. (Got this from CSS-Tricks - thanks guys! 👍)
您可以看到CSS非常簡單。 唯一值得一提的部分是.videoWrapper CSS聲明。 這樣可以確保YouTube嵌入可以響應。 (從CSS-Tricks那里得到了-謝謝大家!👍)
結論 (Conclusion)
And voilà! We're done! 😃
和瞧! 大功告成! 😃
You should now know how to use a public API to get some data which you can then insert on the page easily! Well done! 👏
您現在應該知道如何使用公共API來獲取一些數據,然后可以輕松地將其插入頁面中! 做得好! 👏
This is the first project I did for the #100Days100Projects challenge. You can check out what other projects I've built and what are the rules of the challenge (if you might want to join) by clicking here.
這是我為#100Days100Projects挑戰所做的第一個項目。 您可以通過單擊此處查看我建立了哪些其他項目以及挑戰的規則(如果您想加入)。
You can read more of my articles on www.florin-pop.com.
您可以在www.florin-pop.com上閱讀我的更多文章。
Happy Coding! 😇
編碼愉快! 😇
翻譯自: https://www.freecodecamp.org/news/creating-a-random-meal-generator/
如何制作營養膳食計算器
總結
以上是生活随笔為你收集整理的如何制作营养膳食计算器_如何创建随机膳食生成器的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 1550:花神游历各国
- 下一篇: 【回溯算法】LeetCode的1024活