teleren/devto huggingface dataset:
Don't put business logic in templates
Published: 2024-01-15 11:33:44

---
title: Don't put business logic in templates
published: true
date: 2024-01-10 00:00:00 UTC
tags: 
canonical_url: https://www.oliverdavies.uk/archive/2024/01/10/dont-put-business-logic-in-templates
---

Here is some code from my website:

```
{% set talkCount = 0 %}

{% for talk in data.talks %}
  {% for event in talk.events if 'today'|date('U') >= event.date|date('U') %}
    {% set talkCount = talkCount + 1 %}
  {% endfor %}
{% endfor %}
```

It is business logic responsible for counting the number of talks I've given at different events so I can display it on my Talks page.

It starts at zero, loops over each talk, and increments the talk count if the event is the current day or a past date.

It's only used in a single place, so the same logic isn't duplicated elsewhere.

But it's in the page's Twig template.

It has no test coverage.

If I need to change or refactor it, I'd need to test it again manually.

Don't do this.

## So, what should I do?

It's OK to put simple presentational logic, such as looping over a list or whether to show or hide a value within a template, but not complex business logic.

Business logic should be separated and executed elsewhere. The values should be passed to the template to be rendered.

This makes the business logic easier to test as you can test the logic itself and determine the value passed to the template is correct without being concerned about the templating engine.

In an application, you may need to output a value to a template and a terminal. You'd have one source of truth, such as a Service, Action or Command class that calculates the value before passing it to the appropriate output.

Once the logic is separated, you only need to test it once.

## Here's the thing

In a previous version of my website, I did this by creating a custom Twig function.

It was as simple as adding `` to the template.

All the logic was moved from the template to my custom extension.

The logic was separated.

It had tests.

This is the approach I'd take to achieve the same result for a client application.

For a client, I want to run a test suite and be confident my logic works as expected - now and in the future.

For myself, and for calculating something simple, this is fine.

 P.S. If you're creating a new Drupal module, try my [free Drupal module template](https://github.com/opdavies/drupal-module-template).
Kickstarting Your Coding Journey in 2024: A Beginner's Guide
Published: 2024-01-09 23:56:57

Welcome to the exciting world of coding! As we step into 2024, technology continues to evolve rapidly, making coding a valuable skill to acquire. Whether youre looking to change careers, enhance your current job skills, or simply want to learn something new, this guide is your starting point into the vast universe of programming.

This guide is crafted to be short, simple, and straightforward, recognizing that the abundance of resources available can often be overwhelming for beginners. Weve distilled the information to include only the best and most user-friendly resources available today, ensuring you get a clear and focused start on your coding journey.

**Understanding the Basics:**

Before diving into complex programming languages, its crucial to understand the basics. Coding is all about problem-solving and logical thinking. Free resources like Codecademy and Khan Academy offer introductory courses that can help you grasp the fundamentals of programming logic and concepts.

#### **Choosing a Programming Language:**

Theres a plethora of programming languages out there, each suited for different tasks. As a beginner, you might want to start with Python, known for its simplicity and readability. Websites like [Python.org](http://Python.org) provide excellent tutorials. If youre interested in web development, HTML, CSS, and JavaScript are the go-to languages. Resources like Mozilla Developer Network (MDN) offer comprehensive guides in these areas.

#### **Hands-On Practice:**

Theory is important, but coding is a skill best learned by doing. Platforms like GitHub offer a plethora of open-source projects where you can start contributing. For interactive learning, websites like FreeCodeCamp and Codecademy offer coding exercises and projects that can bolster your understanding and confidence.

#### **Join Coding Communities:**

Joining coding communities can greatly enhance your learning journey. Platforms like Stack Overflow, Reddits r/learnprogramming, and local meetups found on [Meetup.com](http://Meetup.com) can be invaluable for networking, advice, and moral support.

#### **Building a Portfolio:**

As you learn and build projects, its crucial to showcase them. Create a GitHub profile to store your code and projects. If youre into web development, consider building a personal website to showcase your work.

#### **Continuous Learning and Specialization:**

Technology is always evolving, and so should your skills. Once youve got the hang of the basics, consider specializing in a field like data science, mobile app development, or blockchain technology. Websites like Coursera and Udacity offer courses in these advanced topics.

#### **Conclusion:**

Embarking on your coding journey in 2024 might seem daunting at first, but with the plethora of resources available, its more accessible than ever. Remember, every expert was once a beginner.
HIRE A PRIVATE INVESTIGATOR TO TRACK DIGITAL CURRENCY SCAMMERS: GEARHEADENGINEERS SOLUTIONS
Published: 2024-01-09 23:44:36

As a victim of digital currency scam, I sure do understand the frustration you are going through, assuming you are a victim reading this. They made last year terrible and hopeless after being conned a total of $60,000. The police did not do anything so I opted to hire a  private investigator to trace the offenders and recover my money. The fake company approached me with a promise to double my investment. They kept asking for more without allowing me to withdraw my profits and in the end I lost nearly $60,000. I found GearHead Engineers Solutions which is among the best cybersecurity companies. The agents specialize in crypto recovery and they truly display profound knowledge in the area. At first I was nervous because I had just been scammed and heard incidences of people being scammed twice but I decided to take the chance with GearheadEngineers. It felt like luck when the tracked the scammers and sent the entire amount I lost to my account. Look them up on Google, GearHeadEngineers Org and submit your case via the chat or contact information listed.
Day 891 : Hard-Fought Progress
Published: 2024-01-09 23:40:53

_liner notes_:
- Professional : Had a meeting at the beginning of the day. For the rest of the day, I got to work on converting the proof of concept that I made last week into a Web Component. It was a hard-fought process but I got a lot of it done. A majority of the features are working. There's a weird bug with the color selection not updating like it should, but I think that has to do with something not rendering or updating during the proper cycle. That's the main issue whenever I do this. Pretty good day.

- Personal : Went through some tracks for the radio show. Did some research on land for sale and found a couple of spots that look promising. Watched an episode of "Blue Eye Samurai". Got some late night inspiration and worked out some CSS stuff for my side project.

![A road in Moorefield, WV, USA curving to the left with orange, yellow and green leaves on trees on both sides of the road with hills and mountains in the distance.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6mprqnzm6v34udxb9nlj.jpg)

Going to go through some tracks for the radio show. Work on my site project. Looking to end the night watching an episode of "Blue Eye Samurai" and maybe look into some land. Now for dinner.

Have a great night!

peace piece
Dwane / conshus
https://dwane.io / https://HIPHOPandCODE.com
{% youtube u8lhI88ZXOA %}
Advanced Egress Solutions
Published: 2024-01-09 22:37:24

The S-Capepod is permanently placed underneath the mattress. The patient neither sees it , nor feels it. Due to its intuitive design, the patient will be ready for evacuation in a matter of seconds. Just click **[Cape Pod - Advanced Egress Solutions](https://advancedegresssolutions.com/product/evacuation-sheet-s-capepod/)** for more info.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o66dkthhv4lyqr13vd1i.png)
Learning HTML
Tags: html
Published: 2024-01-09 21:32:30

**HTML stands for HyperText Markup Language and is used to create the structure and content of a webpage.**
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tjroeb81c7dd4adizc62.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7rkh9cyznilba5kxpeda.png)


Headings  < h 1> </ h 1>  Go from largest to smallest as it increases. h1 being the largest and h6 being the smallest. 

< div> is short for division. It allows you to group HTML elements to apply the same styles.

Paragraphs (< p >) contain a block of plain text.
< span > contains short pieces of text or other HTML. They are used to separate small pieces of content that are on the same line as other content.
The < em> tag will generally render as italic emphasis.
The < strong> will generally be rendered as bold emphasis.
< br > creates a line break element. (creates space)
< ul > Creates a bulleted list of items that need to be used < li > to make the list.
< ol > creates an ordered list

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pz6fqwwhm4jke0lth9sw.png)

< img > allows you to add an image
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v97fr0n0nmeux7jz5d3w.png)

The alt attribute, which means alternative text, brings meaning to the images on our sites. The alt attribute can be added to the image tag just like the src attribute. The value of alt should be a description of the image.

< video > allows you to display a video that requires a src
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dje3l8r4axfxt84ejyoe.png)

The controls attribute instructs the browser to include basic video controls like pausing and playing.

**HTML Files**
 
< !DOCTYPE html >, the declaration specifying the version of HTML for the browser
The < html > tags that enclose all of your HTML code
The < head > tag that contains the metadata of a webpage, such as its <title>
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3f2twc4shzyc8gx3kwu4.png)
 
< a > anchor element. It is incomplete without the Href attribute. This is to hyperlink to other sites. 
Target attribute requires a value of _blank to make the link open into a new window.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tetklrxzrjg2x9l4siag.png)

wrapping a link around and image instead of just text. 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/upknc09ivs2kfdn3dcd4.png)

Comments begin with <!-- and end with -->. Any characters in between will be ignored by your browser.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hzgg8lteg7mxxpcjhj4v.png)
Check out my new Portfolio Website!
Tags: webdev, portfolio, rust
Published: 2024-01-09 21:27:10

I created my own portfolio website which will contain an about me section,  resume stuff (skills, experience), publications I've done, and a list of my articles from DevTo and my MoKa Reads Blog. 

I hope to expand it as I continue to create more projects, research and curriculum development. 

The website uses a custom web server created using the `rocket` crate along with `tera` templates for dynamic web pages. 

I followed a minimalist style so I could easily have it look well on desktop and mobile. 

You can check it all out at [mustafif.com](https://mustafif.com)
Data Lake Vs Data Warehouse Vs Data Mart
Tags: data
Published: 2024-01-09 21:15:10

Well, data is everywhere every second of every day.As a backend developer, I used to  dodge terms related to data engineering. However, due to a recent project, I've started learning more about it.
<br>
    <img src="https://raw.githubusercontent.com/irakan/my-learning-journey/main/memes/2.jpg" alt="how-docker-works" width="200"/>
<br>
    So, I came across these terms: Data Lake, Data Warehouse, and Data Mart. I will break them down into simple terms that I can understand. 
    
The format will be as follows:
    - Definition: (Definition)
    - Characteristics: (Characteristics)
    - Why it exists: (Why it exists)
    - Tools: (Tools that can be used to implement it)
<br>

1. **Data Lake:**
    - **Definition:** A huge storage space for all raw data (For example: JSON, Videos, Database dumps, etc) where everything is dumped without organization.
    - **Characteristics**:
        - Stores raw data without modification.
        - Store structured, semi-structured, and unstructured data.
        - Can be Used for the entire data lifecycle.
    - **Why it exists:** Data is valuable nowdays and it can be used for many things. So, store it and you can use it later when you need it.
    - **Tools:** 
        - *Free:* Hadoop Distributed File System (HDFS)
        - *Paid:* Amazon S3, Azure Data Lake Storage, Google Cloud Storage
<br><br><br>
2. **Data Warehouse:**
    - **Definition:** An organized storage place where data is structured and cleaned.
    - **Characteristics**:
        - Stores data in a structured way.
        - Requires transformed and cleaned data.
        - Time-variant data, meaning any existing data will be archived after perid of time (Example: 1 year) and stored in the Data Lake.
    - **Why it exists:** Since data is stored in a structured way, it can be used for reporting and analysis.
    - **Tools:** 
        - *Free:* PostgreSQL, MySQL, MariaDB (limitions: not scalable for HUGE data and not optimized for analytics purposes)
        - *Paid:* Amazon Redshift, Google BigQuery
<br><br><br>
3. **Data Mart:**
    - **Definition:** A subset of a Data Warehouse, with a focus on specific topics.
    - **Characteristics**:
        - Users don't need advanced technical knowledge.
        - Subset of a Data Warehouse, smaller and topic-focused.
        - Users have read-only access to specific information.
    - **Why it exists:** Provides users a quick and easy access to data for specific topics.
    - **Tools:** 
        - *Free:* Microsoft Power BI (limited features)
        - *Paid:* Microsoft Power BI, Tableau, QlikView, Looker

**Resources:**
- [Data Lake vs Data Warehouse vs Data Mart](https://www.sprinkledata.com/blogs/data-lake-vs-data-warehouse-vs-data-mart)
Math's in computer science: Graph theory
Tags: beginners, tutorial, learning
Published: 2024-01-09 19:49:56

Graph theory is a pretty big deal in computer science, and often regarded as a topic that just focuses on computer science. However graph theory is so much bigger than just computer science, it is more accurate to say that it is the study of the field of graphs, whose applications in computer science are invaluable to say the least. I hope to enlighten you with this knowledge.  

Firstly I think it is important to explain what we mean by a graph in this context. A graph is something that we use to help define and visualize relationships between components. We do this visually by calling the components "nodes", and the lines that connect them to other components as "edges". An example is below (credit to GeeksforGeeks for the picture)
 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zo364jgqmf9hacjdrsrx.png)

Now it is time to discuss the types of graphs:

- Weighted graph: This is a graph where the edges represent a value, such as maybe the distance from points, or the time is takes to go from point to point. 

- Undirected Graph: A graph where the edges don't point from one node to another, so it is bidirectional relationship.

- Directed Graph: A graph where the edges do point from one node to another to symbolize a one way relationship.

- Trees: Trees are undirected graphs where two nodes are only ever connected by one edge.

But why would we take the time and effort to learn this topic that just seems like a bunch of circles connected by lines. One direct application is GPS. You can model the streets as graphs and this proves to be very useful. Other applications include social networks, computer networks, and even when computers solve sudoku puzzles. 

Great now you know the basics of Graph theory. The topic goes so much deeper so i will need more than one post to delve into this. I hoped you enjoyed reading.
The 1 Thing I Wished I Knew When I Started As a Junior Dev
Tags: junior, frontend, beginners, impostorsyndrom
Published: 2024-01-09 21:02:26

Imagine you're **dating** someone.

His name is Joe; you met on Twitter three months ago.

Now, you can't go a minute without talking.

**The issue?** He lives in another country, and you've never met him.

He can't afford the trip, so you decide to pay for him to come over because you want to see him so badly.

The first meeting is **magical**,  and you fall even more in love. You spend a month together and **decide to get engaged**. 

**Every member of your family is against it**, but still, you want to be with him. In desperation, your family agrees with one condition: you must sign a **prenuptial agreement**. If your husband leaves within 6 months or behaves poorly, the wedding dissolves, and he owes you money.

**Would you secretly hope for Joe to fail or do everything to help him succeed and prove doubters wrong?**

Like me, you'd choose the latter: you've invested so much—your heart, your reputation, hell, your money.

## Similarly, a company that just hired you wants you to succeed so badly because of all the recruiting effort.

A company that hires you is invested in your success. In fact,

- They've _"dated"_ you through recruiting talks, online interviews, etc.

- They flew you over to meet in person (i.e, onsite interviews)

Now, all they want is for you to succeed. They want you to pass the probation period and succeed after. They want to prove to themselves that they made the right decision.

## So, stop being afraid of being found out.

Stop thinking, **_"I'm a fraud"_** or _**"My manager doesn't like me"**_ (except if you have clear proof; in that case, try to change teams).

Always assume that the company wants you to succeed and act accordingly:

- Ask for help when you need it.

- Discuss issues and factors that may lead you to consider leaving with your higher-ups.

Want more of these? Find me on [X/Twitter](https://twitter.com/_ndeyefatoudiop) or on [Substack](https://frontendjoy.substack.com/).
Currying can save passing extra props!
Tags: react, reactjsdevelopment, webdev
Published: 2024-01-09 20:58:19

Before we proceed with using currying in a sample React example to omit passing extra props, do check out **[what currying is](https://dev.to/saksham-malhotra/lets-make-a-curry-426k).**

Let's consider a simple example where we are developing the players section in a game and the player names are editable

```
const Players = () => {
    const [playerNames, setPlayerNames] = useState(["Player 1", "Player 2"]);

    function updatePlayerName(index, name) {
        setPlayerNames((prevPlayers) => {
            prevPlayers[index] = name;
            return [ ...prevPlayers ];
        });
    }

    return (
        <>
            {playerNames.map((playerName, index) => {
                <Player
                    key={index}
                    name={playerName}
                    index={index}
                    updatePlayer={updatePlayerName}
                ></Player>;
            })}
        </>
    );
}
```

Note that we are passing a prop called `index` just to enable updating name at a particular index in the state. But apart from that, there should be no use of index in the child `Player` component.

**How can we avoid passing this extra `index` prop?**

You guessed it right, by using the concept of currying. We can simply curry the `setPlayerName` method as

```
function updatePlayerName(index) {
    return function (name: string) {
        setPlayerNames((prevPlayers) => {
            const updatedPlayers = [...prevPlayers];
            updatedPlayers[index] = name;
            return updatedPlayers;
        });
    };
}
```

and call it in the template as 

```
updatePlayer={updatePlayerName(index)}
```

Note that now the `updatePlayerName` function is invoked inline in the template instead of being just assigned as a reference. This helps return a new curried reference to the function to pass down thus eliminating the need of passing index as an additional prop.

Best of coding!
Shopping for healthy nutrition is like looking for the most appropriate programming tools.
Tags: beginners, programming
Published: 2024-01-09 20:22:57

Imagine you succeeded to overcome your addiction to sugar and started to avoid industrial processed foods along with avoiding any wheat products and products containing pork or milk. No more addicted to sugar you reject any food containing white sugar and glucose/fructose syrup, too. 

Then you walk into a Supermarket selling food in order to get something to eat ... and experience that more than 90% of the shelves is filled with products which you don't need and buy anymore. 

Similar experience you will make after you delved into the concept of [_oOo way_](https://dev.to/ooosys/the-ooo-way-part-1-proof-of-concept-2a9m) of doing things.

All of the sudden the plenty of options to choose from if you reject to obey to foreign rules imposed on you by what advertises as useful and helpful separating what you do from what is actually going on "under the hood" shrinks down to a level far below the 10% you have experienced in the Supermarket. The overwhelming affluence turns into painful scarcity and you become aware that there is no way around as to start from scratch in you want to regain the control over the machine you are using. 

You may be so scared by the vision that you need to start from scratch where you are as good as alone on that path and you may be so scared by the vision that you need to accept that all the past efforts of learning multiple programming languages were waste of time, that you quickly turn away from even only trying to find out if this might be something worth to explore. 

It's OK ... Fear is a very painful emotion and if you decided in your life that the best way of coping with it is to avoid it at any cost, reading up to this point will become from your point of view worth to be described as waste of time. 

Thanks for your attention, the most valuable asset in your portfolio.
Announcing TCG Videos/Podcast
Tags: news
Published: 2024-01-09 20:03:35

Hey everyone!

TCG here with some big news. Thanks to our first hire - Carter (check him out and drop a follow at @thatcomputerguy2) we are able to start our ThatComputerGuy Videos series and Podcast! The format will start slow (veeerrrry slow, maybe once a month) but as we acclimate more to RSS and that kind of thing we should be able to speed it up. Also, noticing my earlier post where I said I was slowing down, thanks to this hire (as well as two others that are going through now) we should be able to make posts more frequently! Alright everyone, TCG Out.
Peace.
I think am creating my own PHP CMS
Tags: webdev, wordpress
Published: 2024-01-09 19:59:35

Hey everyone,
I'm [Frank](https://www.awaflix.ng/author/staff/) and I needed a small kind of advice, will it be nice if I start creating my own PHP Script Content Management System...

Or I should just by a PHP Script from Code Canyon!

Your answers and advice will be appreciated!